[英]How to unit test a function which calls another that returns a promise?
[英]How to test a function which has calls a another API function in it - NodeJS
我有一个 function,里面还有一个 function。 在第二个 function 中,我们正在拨打 API 电话。 那么如何为这种情况编写单元测试呢? 我不想拨打实际的 API 电话,我想模拟它。
const getData = async (data) => {
const res = await got.post(url,{
json: {data}
});
const data = res.data;
return data;
}
function firstFunction(args) {
// perform some operation with args and it's stored in variable output.
let output = args;
let oo = getData(args);
console.log(oo)
}
运行单元测试时,您不必调用真正的 API 调用。 您必须封装您的组件并提供任何外部信息。
使用 jest,您可以模拟http 调用并返回您想要的内容。 您还可以检查是否已调用模拟。
import { got } from "anyplace/got";
import { firstFunction } from "anyplace2";
jest.mock("anyplace/got", () => ({
// here you provide a mock to any file that imports got to make http calls
got: {
// "mockResolvedValue" tells jest to return a promise resolved
// with the value provided inside. In this case {data: 'what you
// want here'}
post: jest.fn().mockResolvedValue({data: 'what you want here'});
}
}));
describe('My test', () => {
beforeEach(() => {
// This will clear all calls to your mocks. So for every test you will
// have your mocks reset to zero calls
jest.clearAllMocks();
});
it('Should call the API call successfully', () => {
// execute the real method
firstFunction({arg: 1});
// check that the API has been called 1 time
expect(got.post).toHaveBeenCalledTimes(1);
expect(got.post).toHaveBeenCalledwith("myurlhere", {data: {arg: 1}});
})
});
您可以使用 setTimeout 模拟它,我进一步提供了一个模拟响应,因此在 1000 毫秒后它将使用此用户数组发送 Promise
const getData = () => {
return new Promise((resolve, reject) => {
setTimeout(resolve({
users: [
{ name: "Michael" },
{ name: "Sarah" },
{ name: "Bill" },
]
}), 1000)
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.