小编ayo*_*ayo的帖子

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

我尝试使用 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' …
Run Code Online (Sandbox Code Playgroud)

typescript jestjs ts-jest

2
推荐指数
1
解决办法
4873
查看次数

标签 统计

jestjs ×1

ts-jest ×1

typescript ×1