Probably a bug
When using cy.fixture("users/admin").as("adminData");
I can't access adminData
I should be able to access this.adminData
Call this.adminData.email
after a fixture has been aliased
describe("Knowledge Base Application", () => {
it("Admin should be able to login", () => {
cy.fixture("users/admin").as("adminData");
cy.visit("/login");
cy
.get('input[name="email"]')
.type(this.adminData.email)
.should("have.value", this.adminData.email);
cy
.get('input[name="password"]')
.type(this.adminData.password)
.should("have.value", this.adminData.password);
cy.get("form").submit();
cy.location("pathname").should("eq", "/home");
});
});
cypress/fixtures/users/admin.js
const admin = {
name: "Valentino",
email: "[email protected]",
password: "secret"
};
Not a bug. Cypress commands are async. It's impossible for this.adminData
to be defined at the moment you're using it.
This doc explains this exact scenario: https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Aliases
The reason OP probably though it was a bug is because the docs for fixture claim the following is valid on it's own:
cy.fixture('users.json').as('usersData')
It is valid on its own, so long as by the time you access it with this.*
, you've nested those cypress commands in a .then()
.
Alternatively you could use cy.get('@usersData').then((users) => ... )
I agree, the doc isn't clear about that. I did the same mistake.
I created a new issue in our docs to document this better here: https://github.com/cypress-io/cypress-documentation/issues/722. Our documentation is open source and contributions are welcome. 馃槃
@brian-mann Any idea why this is not working (v3.1.0):
describe('Knowledge Base Application', () => {
before(() => {
cy.fixture('users/admin').as('adminData')
})
it('test1', () => {
cy.get('@adminData')
.then(adminData => { // able to read adminData
cy.log(adminData)
})
})
it('test2', () => {
cy.get('@adminData')
.then(adminData => { // **throws exception: CypressError: cy.get() could not find a registered alias for: '@adminData'. You have not aliased anything yet.**
cy.log(adminData)
})
})
})
This works fine if I move the fixture setup from before to beforeEach.
@aaditya-kumar-harness For some reason the fixtures you are initializing in before() method will only be accessable from the first test (Cypress implemented it like that.) If you want to access from all of it, you have to use beforeEach.
@aaditya-kumar-harness relevant thread: https://github.com/cypress-io/cypress/issues/665
It works. Being asynchronous you have to wait for the fixture to be loaded
cy.fixture("users/admin.json").as("admin")
cy.get('@admin')
.then((admin) => {
cy.get("#selector1")
.type(admin.username)
cy.get("#selector2")
.type(admin.password)
})
Most helpful comment
I agree, the doc isn't clear about that. I did the same mistake.