Jest.js 如何测试一个调用了另一个API函数的函数- NodeJS

fsi0uk1n  于 2023-01-28  发布在  Jest
关注(0)|答案(2)|浏览(210)

我有一个函数,它里面有另一个函数,在第二个函数中,我们调用了一个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)
}
kmbjn2e3

kmbjn2e31#

当运行单元测试时,你必须调用真实的的API调用。你必须封装你的组件并提供任何外部信息。
使用jest你可以mockhttp调用并返回你想要的结果。你还可以检查mock是否被调用过。

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}});
 })
});
8i9zcol2

8i9zcol22#

您可以使用setTimeout来模拟它,我还提供了一个模拟响应,因此在1000ms后,它将发送一个带有此用户数组的Promise

const getData = () => {
    return new Promise((resolve, reject) => {
        setTimeout(resolve({
            users: [
                { name: "Michael" },
                { name: "Sarah" },
                { name: "Bill" },
            ]
        }), 1000)
    })
}

相关问题