我正在使用npm请求,如何模拟request.post我需要测试错误场景,状态码不是200场景和成功流程。
1 request.post(reqObject, (error: Error, response: any, body: any) => {
2 if (error) { return reject(error); }
3 if (response.statusCode !== 200) {
4 return reject('Invalid status code <' + response.statusCode + '>');
5 }
6 return resolve(JSON.parse(body));
7 });
request
对象可以被jest.mock('request')
模拟。
像这样:
const request = require("request");
jest.mock('request', () => {
return {
post: () => {
console.log("mocked");
// or something like jest.fn()
}
};
});
test('test description', () => {
// request.post within fetchData has been mocked
// await fetchData();
});