如何在got.post处重写返回方法使用笑话模拟,所以我可以调用json方法

问题描述

我尝试用玩笑来测试我的脚本(打字稿)

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


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

和我的测试

// 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);
});

当我尝试运行测试时(npm test) 我得到了错误

TypeError: Cannot read property 'json' of undefined

如何在玩笑测试中处理代码?

解决方法

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

Got npm package实现了两种调用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' })
});

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...