I am using Cypress component testing. I currently have the below code to setup one of my component test suites, loading a fixture once (before) then mounting it each time (beforeEach)
before(() => {
cy.fixture('entries/index').as('index').then( (index) => {
index.forEach( (item) => {
item.created_at = DateTime.fromISO(item.created_at)
})
})
})
beforeEach(function() {
mount(component, {
propsData: {'index':this.index},
})
})
This works exactly as expected for the first test that is run, but fails for the second test as 'this.index' becomes undefined for the second test. Through dumping the output this happens after the first test completes rather than when the component is mounted.
it("Does foo",() => {
cy.contains('foo')
})
it("Does bar", () => {
cy.contains('bar')
})
The first test works, the second test the component is mounted with empty data. What am I doing wrong? I could move the fixture to the beforeEach from the before, but then the fixture file is read multiple times when it only needs to be done once.
This is the default behavior for Mocha, so aliases are cleared after each test. You can read more about it from the Cypress docs. Hence moving to beforeEach()
should solve the issue for you.
beforeEach(function() {
cy.fixture('entries/index').as('index').then((index) => {
index.forEach((item) => {
item.created_at = DateTime.fromISO(item.created_at)
})
})
})