【问题标题】:Mocking axios in Jest returns axios is not defined在 Jest 中模拟 axios 返回 axios 未定义
【发布时间】:2020-10-24 22:30:00
【问题描述】:

我看到了类似的问题,但它们实际上并没有解决我在寻找什么。

所以我在 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

【问题讨论】:

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


    【解决方案1】:

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

    解决方案是在您的测试中将您的 axios mock 设置为 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-26
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-21
      • 2019-07-22
      • 2023-04-02
      相关资源
      最近更新 更多