问题描述
我尝试用玩笑来测试我的脚本(打字稿)
// 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请求的方式:
-
const response = got('http://google.com',{ method: 'get' });
-
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' })
});