Cypress Component Testing #985
Replies: 2 comments 1 reply
-
I also had the same problem with that: seems like calls to the store from component was not registered at all from the tests' side. To solve this issue I've decided to create a custom Cypress command, which can be used to get instance of the store already created in import { createPinia, setActivePinia } from 'pinia'
import { useStore } from 'path/to/your/store'
setActivePinia(
createPinia()
)
const store = useStore()
Cypress.Commands.add('getStore', () => store)
declare global {
namespace Cypress {
interface Chainable {
getStore()
}
}
} You can probably use describe('getStore example', function() {
beforeEach(function() {
cy.getStore().as('store')
cy.mount(AmendmentSelector)
})
it('calls the store to populate the amendments list on mount', function() {
// NOTE: aliases are available as 'this.*'
// as long as fat arrow functions ('() => {}') are not used.
cy.spy(this.store, 'getCurrentAmendments');
// NOTE: you can't rely on 'this.*' to be invoked in order after other Cypress commands,
// so its better to wrap them up in one of them,
// aliases make it easy, sadly you seem to lose information about the type.
cy.get('@store')
.then(store => store.availableAmendments = []);
cy.get('@store')
.its('getCurrentAmendments')
.should('be.calledOnce')
cy.get('@store')
.its('availableAmendments')
.should('have.lengthOf', 2)
});
}) Of course it needs to be adjusted if you plan to use multiple stores but it should be easy from now on. Let me know if I'm missing something or if anyone has a better solution! |
Beta Was this translation helpful? Give feedback.
-
Reading the answer from @EtiamNullam pointed me to a solution with describe('test my store spies', () => {
beforeEach(() => {
createTestingPinia({
initialState: {
// ... initialize your store here
},
createSpy: cy.spy,
});
cy.wrap(useStore()).as('store');
});
it('mounts without errors', () => {
cy.mount(MyComponentUsingTheStore);
cy.get('@store').its('getAll').should('be.calledOnce');
});
}); |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
Looking for some help with component testing with Cypress and Pinia.
I've written a quick test.
With this I get the failed assertion that store.getCurrentAmendments hasnt been called, however it does call it on mount of my component. It seems like I'm injecting a different version of the store to what my component is actually using. If i call store.getCurrentAmendments inside my actual test it works.
I would usually use CreateTestingPinia() but it only works in jest, any ideas?
Beta Was this translation helpful? Give feedback.
All reactions