我正在尝试测试登录用户的 API 调用。现在我想要的是发送 email and password
作为输入并期望对象与 { success: true, message: 'logged in'}
。通过我当前的测试,我可以使用输入 { success: true, message: 'logged in' }
进行测试,但不能使用 email and password
。
下面是我在单独文件中的 api 调用。
import axios from 'axios';
export function authService(user, apiEndpoint) {
return axios.post(`http://localhost:3000/api/v1/${apiEndpoint}`,
user,
{
headers: {
'Content-Type': 'application/json',
}
}
)
.then(response => {
return response;
})
.catch(error => {
return error;
});
}
这是 axios 的模拟文件。
module.exports = {
post: (apiEndpoint, data) => {
console.log(data) // returns { email: 'blah@email.com', password: '123123', } which I want.
return Promise.resolve({
success: true,
message: 'logged in',
});
}
};
这是测试。
it('a post request should be made', () => {
const loginSpy = jest.spyOn(axios, 'post');
authService({ email: 'blah@email.com', password: '123123', }, 'login') // authService expects email and password as input.
.then(response => response)
.catch(error => error)
.finally(() => {
console.log(loginSpy.mock.results[0].value); // this returns Promise { { success: true, message: 'logged in' } } **this is what I want to test**
expect(loginSpy).toHaveBeenCalled();
// expect(loginSpy.mock.results[0].value).resolves().toEqual({ // I tried this but it fails
// success: true,
// message: 'logged in',
// });
// expect(loginSpy.mock.calls[0][1]).toEqual({ // This is passed only if I pass { success: true, message: 'logged in' } to authService but authService does not expect this kind of object.
// success: true,
// message: 'logged in.',
// });
})
});
所有内容都在上面的测试用例中进行了注释。请帮我测试 API 调用的输入和输出。我该怎么做?
答案 0 :(得分:0)
如果您使用 jest.spyOn()
来监视和模拟 axios.post()
方法及其解析值。您不需要使用 __mocks__/axios.js
模拟文件。为避免混淆,请勿将它们一起使用。
例如
authService.ts
:
import axios from 'axios';
export function authService(user, apiEndpoint) {
return axios
.post(`http://localhost:3000/api/v1/${apiEndpoint}`, user, {
headers: {
'Content-Type': 'application/json',
},
})
.then((response) => {
return response;
})
.catch((error) => {
return error;
});
}
authService.test.ts
:
import axios from 'axios';
import { authService } from './authService';
describe('68242850', () => {
it('should return response', async () => {
const postSpy = jest.spyOn(axios, 'post').mockResolvedValueOnce({
success: true,
message: 'logged in',
});
const actual = await authService({ email: 'blah@email.com', password: '123123' }, 'login');
expect(actual).toEqual({ success: true, message: 'logged in' });
expect(postSpy).toBeCalledWith(
'http://localhost:3000/api/v1/login',
{ email: 'blah@email.com', password: '123123' },
{
headers: {
'Content-Type': 'application/json',
},
}
);
postSpy.mockRestore();
});
it('should handle error', () => {
// you can figure it out based on above exmple
});
});
单元测试结果:
PASS examples/68242850/authService.test.ts (9.331 s)
68242850
✓ should return response (4 ms)
✓ should handle error
----------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------------|---------|----------|---------|---------|-------------------
All files | 80 | 100 | 66.67 | 80 |
authService.ts | 80 | 100 | 66.67 | 80 | 14
----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 10.49 s