如何重写got.post()处的返回方法(使用jest模拟),以便我可以调用json方法

ayo*_*ayo 2 typescript jestjs ts-jest

我尝试使用 jest 来测试我的脚本(打字稿)

// api.ts
import got from "got";


export const run = async () => {
  const body = await got.get('https://jsonplaceholder.typicode.com/posts/1').json();
  return body;
};
Run Code Online (Sandbox Code Playgroud)

和我的测试

// api.test.ts
import { run } from "../api";
import got from "got";
import { mocked } from "ts-jest/dist/util/testing";

jest.mock("got");

test("using another got", async () => {
  const response = {
    get: jest.fn(),
  };
  mocked(got).mockResolvedValue(response);

  const result = await anotherGot();
  console.log(result);
  // expect(result).toBe(response.body);
});
Run Code Online (Sandbox Code Playgroud)

当我尝试运行测试 ( npm test) 时出现错误

TypeError: Cannot read property 'json' of undefined
Run Code Online (Sandbox Code Playgroud)

如何处理 jest test 中的代码?

noa*_*700 9

您试图模拟函数got本身(这也是一个函数)。但你需要模拟got.get函数。

让 npm 包实现了两种调用 HTTP GET 请求的方式:

  1. const response = got('http://google.com', { method: 'get' });
  2. const response = got.get('http://google.com');

因此,如果你想模拟你的,got.get(...)你需要模拟got.get而不是got它本身(用例#2):

// api.test.ts
// import { run } from "../api";
import got from "got";
import { mocked } from "ts-jest/utils";

jest.mock("got");

test("using another got", async () => {
    const mockedGot = mocked(got);

    // use case #1 - using got module directly
    mockedGot.mockReturnValue({
        json: () => Promise.resolve({ dataAttr1: 'val11111' }),
    } as any)

    const response1 = got('http://www.google.com', { method: 'get' });
    const data1 = await response1.json();
    expect(data1).toEqual({ dataAttr1: 'val11111' })

    /*******************************************************************/

    // use case #2 - using got.get "alias"
    // this is your case :)
    mockedGot.get = jest.fn().mockReturnValue({
        json: () => Promise.resolve({ dataAttr1: 'val22222' }),
    } as any);

    const response2 = got.get('http://www.google.com');
    const data2 = await response2.json();
    expect(data2).toEqual({ dataAttr1: 'val22222' })
});
Run Code Online (Sandbox Code Playgroud)