简体   繁体   中英

How to unitest npm `request.post` using jest

I am using npm request , How to mock request.post I need to test the error scenario, statuscode not 200 scenario and the success flow.

1 request.post(reqObject, (error: Error, response: any, body: any) => {
2     if (error) { return reject(error); }
3     if (response.statusCode !== 200) {
4         return reject('Invalid status code <' + response.statusCode + '>');
5     }
6     return resolve(JSON.parse(body));
7 });

The request object can be mocked by jest.mock('request') .

Something like this:

const request = require("request");
jest.mock('request', () => {
    return {
        post: () => { 
            console.log("mocked"); 
            // or something like jest.fn()
        }
    };
});

test('test description', () => {
    // request.post within fetchData has been mocked
    // await fetchData(); 
});

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