简体   繁体   中英

How to mock a 'request' node module for testing in jest

I am new to writing test cases in jest and i wanted to test 'mark' function and want to mock 'request' node module. let's say this file's name is app.js and test file will be app.test.js

Can someone tell how to write its test case?

const request = require("request")

var test = {
    mark: function(data,cb){
        data.url = "localhost"
        request(data, function(err,response,body){
            if(!response){
                err.response = false
            }
            cb(err,body)
        })
    }

}

module.exports = test;

If I understand your question correctly, you are asking two questions:

  1. How to write the test and mock the request
  2. What test cases you should write

Regarding the mock, I recommend using nock which is an npm module for mocking.network requests.

To the second question, I believe that you should map the logic in the function and create the test cases from there. Think about the function, look at every if else/calculation/loop and it's possible outcomes and create test cases from there.

The mark function doesn't have a lot of logic, it's send a request, updates the err variable according to the response and calling the callback.

The only outcome we can test to to see that if the request works, the cb is called correctly without modifications. And if the request returns empty, change the err var and call the callback.

To do so we need to mock the request and return a response to match the test case and validate that the cb was called correctly (can be done with a mock).

Test case example:

The test case may be a bit abstract since I don't have the real use case of the function but it shows the point

it("Should mark response false when it does not exist", () => {
    const DATA = {} // your data object
    const callback = jest.fn();

    nock('localhost')
        .get('/example')
        .reply(500) // Exaple of mocking the resonse. Custom it to be more specific depending on mark.
        
    test.mark(DATA, callback);


    // Verify that the function was called.
    expect(callback).toHaveBeenCalled();
    // Verify that `err.response` was false.
    expect(callback.mock.calls[0][0].response).toBe(false)
})

You can read more about mocking and verifying parameters here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM