您可以使用jest.spyOn(object, methodName) 和mockFn.mockImplementation(fn) 根据url 参数模拟具有不同解析值的axios.get() 方法。
此外,从文档 Concurrency (Deprecated) 中,我们知道 axios.all() 和 axios.spread() 方法已被弃用。使用Promise.all 替换它们。
main.ts:
import axios from 'axios';
interface APIGatewayProxyEvent {}
interface APIGatewayProxyResult {}
export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
const options = {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json;charset=UTF-8',
authorization: 'Token',
},
};
const respData = await axios
.all([
axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5', options),
axios.get('https://jsonplaceholder.typicode.com/posts?_limit=5', options),
])
.then(axios.spread((todos, posts) => ({ todos, posts })))
.catch((err) => console.error(err));
return { statusCode: 200, body: JSON.stringify(respData) };
};
main.test.ts:
import { handler } from './main';
import axios from 'axios';
describe('69096350', () => {
test('should pass', async () => {
const axiosGetSpy = jest.spyOn(axios, 'get').mockImplementation(async (url) => {
if (url === 'https://jsonplaceholder.typicode.com/todos?_limit=5') {
return [1, 2, 3, 4, 5];
} else if (url === 'https://jsonplaceholder.typicode.com/posts?_limit=5') {
return ['a', 'b', 'c', 'd', 'e'];
}
});
const actual = await handler({});
expect(actual).toEqual({
statusCode: 200,
body: JSON.stringify({ todos: [1, 2, 3, 4, 5], posts: ['a', 'b', 'c', 'd', 'e'] }),
});
expect(axiosGetSpy).toBeCalledWith('https://jsonplaceholder.typicode.com/todos?_limit=5', {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json;charset=UTF-8',
authorization: 'Token',
},
});
expect(axiosGetSpy).toBeCalledWith('https://jsonplaceholder.typicode.com/posts?_limit=5', {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json;charset=UTF-8',
authorization: 'Token',
},
});
axiosGetSpy.mockRestore();
});
});
测试结果:
PASS examples/69096350/main.test.ts (7.535 s)
69096350
✓ should pass (4 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 88.89 | 100 | 75 | 85.71 |
main.ts | 88.89 | 100 | 75 | 85.71 | 20
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 8.035 s, estimated 9 s
Ran all test suites related to changed files.