Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock this http request using jest?

I am new to using Jest for unit tests. How can I mock this simple http request method "getData"? Here is the class:

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

    }

}

I am trying to mock "getData" so I can write a unit test for "logData". Do I need to mock out the entire "got" module? Thanks.

like image 943
Ben R Avatar asked Apr 25 '26 05:04

Ben R


1 Answers

If you change invoking got to got.get you should be able to have a working test like so:

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

like image 196
Christian Avatar answered Apr 26 '26 23:04

Christian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!