首页 > 解决方案 > 如何使用 jest 模拟这个 http 请求?

问题描述

我是使用 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”编写单元测试。我需要模拟整个“得到”模块吗?谢谢。

标签: node.jsunit-testingasynchronousjestjsmocking

解决方案


如果您将调用更改gotgot.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);
    })
})


推荐阅读