如何使用Jest模拟此HTTP请求?

9

我是初次使用Jest进行单元测试。如何模拟这个简单的HTTP请求方法“getData”?以下是类代码:

const got = require("got")

class Checker {


    constructor() {
        this.url

        this.logData = this.logData.bind(this);
        this.getData = this.getData.bind(this);

    }

    async getData(url) {
        const response = await got(url);
        const data = await response.body;
        return data;
    }

    async logData(first, second, threshold) {
        
        let data = await this.getData(this.url)
        
        console.log("received " + data.body);

    }

}

我想模拟“getData”,以便为“logData”编写单元测试。我需要将整个“got”模块都模拟吗?谢谢。


你有任何测试代码可以分享吗? - Christian
这个回答解决了你的问题吗?https://stackoverflow.com/a/63645925/360674 - Christian
很遗憾,无法做到,因为它使用的是TypeScript,而我正在使用JavaScript(与Node一起)。 - Ben R
我可能能够适应它,但我不知道在哪里获取那个“mocked”函数。 - Ben R
3个回答

8
如果你将调用 got 改为 got.get,那么你应该能够像这样拥有一个可工作的测试:
const got = require('got');
const Checker = require('../index.js');

describe("some test", () => {
    beforeEach(() => {
        jest.spyOn(got, 'get').mockResolvedValue({ response: { body: { somekey: "somevalue" } } } );
    });
    it("works", async () => {
        new Checker().getData();
        expect(got.get).toBeCalledTimes(1);
    })
})


3

一种方法是使用依赖注入。不直接调用“got”,而是在类构造函数中“要求它”,并将其分配给一个私有变量。然后,在单元测试中,传递一个模拟版本,它将返回您想要的内容。

const got = require("got");
class Checker {
    constructor(gotService) {
        this.got = gotService;
        this.logData = this.logData.bind(this);
        this.getData = this.getData.bind(this);
    }

    async getData(url) {
        const response = await this.got(url);
        const data = await response.body;
        return data;
    }

    async logData(first, second, threshold) {        
        let data = await this.getData(this.url)        
        console.log("received " + data.body);
    }
}

//real code
const real = new Checker(got);

//unit testable code
const fakeGot = () => Promise.resolve(mockedData);
const fake = new Checker(fakeGot);

我们正在做的事情如下:

  1. 将“Inject”注入到类中。
  2. 在类中调用我们注入的版本,而不是直接调用原始版本。
  3. 当进行单元测试时,传递一个假版本,以执行您想要的操作。

2

您可以直接将此内容包含在测试文件中。然后触发进行Http请求的测试,这将作为有效载荷提供。

global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve({ data: { eth: 0.6, btc: 0.02, ada: 1 } }),
  })
);

it('should return correct mock token values', async () => {
  const addresses = ["mockA", "mockB", "mockC"];
  const res = await getTokenData(addresses);
  expect(res.data).toEqual({ eth: 0.6, btc: 0.02, ada: 1 });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接