【问题标题】:Vue, Jest, Axios.create(), and Modularized API Methods. How to Spy?Vue、Jest、Axios.create() 和模块化 API 方法。如何进行间谍活动?
【发布时间】: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

【问题讨论】:

    标签: vue.js axios jestjs


    【解决方案1】:

    jest.createMockFromModule() 不会自动覆盖导入,但 jest.mock() 会。

    用返回模拟对象的工厂模拟目标模块(即MyApi.js),然后在测试中require它以访问模拟:

    jest.mock('../services/MyApi', () => ({
      orders: {
        exportData: jest.fn(() => Promise.resolve())
      }
    }))
    
    describe('Testing component', () => {
      it('click directive', async () => {
        const wrapper = shallowMount(ExportOrdersButton)
        await wrapper.find('button').trigger('click')
        expect(require('../services/MyApi').orders.exportData).toHaveBeenCalled()
      })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      • 2020-03-23
      • 2018-05-02
      • 2019-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多