我想这样测试。
案例1:错误
无法监视内部属性,因为它不是函数;未定义,而是给定。
- 组件.vue
export default {
setup() {
function outer() {
inner();
}
function inner() {
// do something for only outer function
}
return { outer };
}
};
- 组件.spec.js
it('what can I do?', () => {
wrapper.vm.inner = jest.fn(); // throw error
wrapper.vm.outer();
expect(wrapper.vm.inner).toBeCalled();
});
案例2:错误
- 组件.vue
export default {
setup() {
function outer() {
inner();
}
function inner() {
// ...
}
return { outer, inner }; // add inner
}
};
- 组件.spec.js
it('what can I do?', () => {
wrapper.vm.inner = jest.fn();
wrapper.vm.outer();
expect(wrapper.vm.inner).toBeCalled();
});
- expect(jest.fn(((.toBeCalled((
- 预期调用数:>=1
- 已接电话数:0
情况3:通过
it('what can I do?', () => {
wrapper.vm.outer = jest.fn(() => wrapper.vm.inner());
jest.spyOn(wrapper.vm, 'inner');
wrapper.vm.outer();
expect(wrapper.vm.inner).toBeCalled();
});
这个案子不好看。。。
我不能得到";inner((";而不将其包括在";return";?
这些方法在选项api中实现时通过。但我只想使用setup((。
自我回答
我找到了一条路。我上了这样的课。
Util.js
class Util {
outer() {
this.inner();
}
inner() {
// do something...
}
}
组件.vue
setup() {
const util = reactive(new Util());
function call() {
util.outer();
}
return { util, call };
}
组件.spec.js
it('is this way correct?', () => {
jest.spyOn(wrapper.vm.util, 'outer');
jest.spyOn(wrapper.vm.util, 'inner');
await wrapper.vm.call();
expect(wrapper.vm.util.outer).toBeCalledTimes(1);
expect(wrapper.vm.util.inner).toBeCalledTimes(1);
});