【发布时间】:2021-03-28 04:21:07
【问题描述】:
我正在测试一个 Vue 组件,它有一个 method(),它用 Axios 调用一个模块,它调用另一个。
组件内部的方法如下:
// Component.vue
methods: {
myMethod(){
return MyAPI.orders
.exportData(requestData)
.then(() =>{
this.showExportModal();
});
}
...
MyAPI.js 看起来像:
export const apiClient = axios.create({
baseURL: `${baseUrl}/api/v2/`,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
const methods = {
orders: {
exportData(payload) {
return apiClient
.post('export',payload)
虽然这工作得很好,但我没有找到一种方法来正确测试组件而不为它创建一个临时模拟。
我正在尝试使用Jest.createMockFromModule,但以这种方式使用它没有运气:
// test.spec.js
const myAPI = jest.createMockFromModule('../services/myAPI');
const wrapper = shallowMount(ExportOrdersButton, {
store,
i18n,
});
[...]
it('should trigger a network request when clicked', async () => {
const button = wrapper.find('button').element;
button.click();
await Vue.nextTick()
expect(myAPI.default.orders.exportData).toHaveBeenCalled()
});
但是尽管调用了该方法,但测试并没有看到它:
Expected number of calls: >= 1
Received number of calls: 0
【问题讨论】: