Javascript 使用create和post、jestjs模拟axios
我目前意识到,在使用Javascript 使用create和post、jestjs模拟axios,javascript,node.js,unit-testing,jestjs,axios,Javascript,Node.js,Unit Testing,Jestjs,Axios,我目前意识到,在使用jestjs检查api时,不应该直接通过网络请求调用api 我一直在看一些帖子+youtube教程,例如,但仍然有点困惑,现在我确定如何让它工作 我创建了一个注册api,并希望对其进行测试,在阅读了模型文档等之后。我的文件夹结构是这样的 这就是我的base\u axios/index.js的样子,base\u URL就像http://localhost:3000 const axios = require('axios'); const { BASE_URL } = re
jestjs
检查api时,不应该直接通过网络请求调用api
我一直在看一些帖子+youtube教程,例如,但仍然有点困惑,现在我确定如何让它工作
我创建了一个注册api,并希望对其进行测试,在阅读了模型文档等之后。我的文件夹结构是这样的
这就是我的base\u axios/index.js的样子,base\u URL
就像http://localhost:3000
const axios = require('axios');
const { BASE_URL } = require('../base');
const baseOption = {
// without adding this, will not be able to get axios response status
validateStatus: function (status) {
return status >= 200 && status <= 503;
},
baseURL: BASE_URL,
headers: { 'Content-Type': 'application/json' },
};
module.exports = axios.create(baseOption);
模拟/axios.js
routes/auth/register.js
我不知道调用了哪个api调用,te响应给了我undefined
还从jestexpect(jest.fn())获取此错误。toHaveBeenCalledWith(…expected)
提前感谢有意见和建议的人
PS
jest.config.js
您可以模拟axios及其实现,如下所示:
jest.spyOn(axios, 'post').mockImplementation();
例如:
test('calls axios for registration', async () => {
const mockDataRequest = {};
const mockPostSpy = jest
.spyOn(axios, 'post')
.mockImplementation(() => {
return new Promise((resolve) => {
return resolve({
data: {},
});
});
});
expect(mockPostSpy).toHaveBeenCalledTimes(1);
expect(mockPostSpy).toBeCalledWith(
`/auth/register`,
expect.objectContaining(mockDataRequest)
);
})) 你能添加jest配置文件吗,想检查根目录的值,如这里指定的@SanketPhansekar我有一个jest.config.js
我编辑了我的帖子const response=wait Auth.register()
当然会返回undefined,因为它不返回任何内容。尝试从request.post('/auth/register',data)
@fubar返回承诺,但仍然没有任何结果。
const Auth = require('../../apis/auth');
const mockAxios = require('axios');
test('calls axios for registration', async () => {
// this should give me an error and show which api has been called
expect(mockAxios.post).toHaveBeenCalledWith('what is the api');
const response = await Auth.register();
console.log(response, 'response'); // response here gives me undefined
});
module.exports = {
clearMocks: true,
coverageDirectory: "coverage",
// The test environment that will be used for testing
testEnvironment: "node",
};
jest.spyOn(axios, 'post').mockImplementation();
test('calls axios for registration', async () => {
const mockDataRequest = {};
const mockPostSpy = jest
.spyOn(axios, 'post')
.mockImplementation(() => {
return new Promise((resolve) => {
return resolve({
data: {},
});
});
});
expect(mockPostSpy).toHaveBeenCalledTimes(1);
expect(mockPostSpy).toBeCalledWith(
`/auth/register`,
expect.objectContaining(mockDataRequest)
);