在Jest中模拟axios返回axios未定义

时间:2020-07-04 10:58:37

标签: vue.js mocking jestjs axios vue-test-utils

我见过类似的问题,但它们实际上并没有解决所寻找的问题。

因此,我正在app.js中为我的Vue应用程序全局使用axios,例如window.axios = require('axios')

然后在auth.js中我有这个

export function login(credentials){
    return new Promise((res,rej) => {
        axios.post('/api/auth/login', credentials)
            .then((response) => {
                res(response.data);
            })
            .catch((err) => {
                rej("Wrong email or password");
            })
    });
}

在登录页面上正常工作

但是在我的测试脚本中

jest.mock("axios", () => ({
    post: jest.fn(() => Promise.resolve({data:{first_name:'James','last_name':'Nwachukwu','token':'abc123'}}))
}));


    import axios from 'axios'
    import {login} from '../helpers/auth'
    it("it logs in when data is passed", async () => {
        const email='super@gmail.com'
        const password='secret';
        const result=await login({email,password});
        expect(axios.post).toBeCalledWith('/api/auth/login',{"email": "super@gmail.com", "password": "secret"})
        expect(result).toEqual({first_name:'James','last_name':'Nwachukwu','token':'abc123'})
    })

显示未定义axios

但是如果我将auth.js更改为

import axios from 'axios'
export function login(credentials){
    return new Promise((res,rej) => {
        axios.post('/api/auth/login', credentials)
            .then((response) => {
                res(response.data);
            })
            .catch((err) => {
                rej("Wrong email or password");
            })
    });
}

通过测试。我如何运行测试而不必在每个vue文件上导入axios

1 个答案:

答案 0 :(得分:0)

我刚才也遇到了同样的问题。我还在 app.js 中通过 window.axios = require('axios'); 包含 axios。

解决方案是在测试中将 axios 模拟设置为 window.axios。所以而不是这个(不正确):

axios = {
    post: jest.fn().mockName('axiosPost')
}

const wrapper = mount(Component, {
    mocks: {
        axios: axios
    }
})

当您的组件代码调用 axios.whatever 时,它确实调用了 window.axios.whatever(据我所知),因此您需要在测试环境中进行镜像:

window.axios = {
    post: jest.fn().mockName('axiosPost')
}

const wrapper = mount(Component, {
    mocks: {
        axios: window.axios
    }
})

在你的测试中:

expect(window.axios.post).toHaveBeenCalled()