Setup: vue, jest & vue-test-utils;
I have a Vue single-file-component with an external dependency - a function (included via import
in the file). That function gets called once one of the component's props gets truthy like this:
import { dependency } from '/path';
...
props: {
myProp: {type: Boolean}
},
...
watch: {
myProp() {
if (this.myProp) dependency();
}
}
The component works well. What doesn't work - is the test I am trying to write. It either fails on no assetions or undefined function name. What is the right way to mock external dependencies in a jest test? My test ("it" part) looks like this:
// tried to replace dependency on component instance like
// const spy = jest.spyOn(myComponent, 'dependency');
// tried to replace stupidly
// const dependency = jest.fn();
it('some description', async () => {
expect.hasAssertions();
const wrapper = mount(myComponent, {
props: {
myProp: true,
},
// tried to pass in data() {} section here with mocked function to call it later as this.dependency
data() {
return {
dependency: jest.fn()
};
}
// tried to pass in global.mocks with dependency defined
global: {
mocks: {
dependency: jest.fn()
}
}
});
expect(wrapper.exists()).toBe(true);
// with any / both of them or w/o
await wrapper.vm.$nextTick();
await flushPromises();
expect(<spy | dependency >).toHaveBeenCalledTimes(1);
});
Any advice is appreciated.
CodePudding user response:
Found a workaround. Made external dependency into an instance method like
...
props: {
myProp: {type: Boolean}
},
...
watch: {
myProp() {
if (this.myProp) this.dependency();
}
}
...
methods: {
dependency
}
and then in the test I mocked this method like:
expect.hasAssertions();
const wrapper = mount(myComponent);
jest.spyOn(wrapper.vm, 'dependency'); // mock the method
await wrapper.setProps({ isOpen: true }); // let DOM be updated
expect(wrapper.vm.dependency).toHaveBeenCalledTimes(1); // assertion