【发布时间】: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