Home > Software design >  Mock api request Jest NodeJs
Mock api request Jest NodeJs

Time:08-11

I'm trying to test the following code:

adapter.js
    async function adapt(message) {
      let parser = JSON.parse(message.content.toString());
      let  apiResult = await api(parser.id);
      let result = apiResult.data.data;
      return adapptedMessage = {"id": result.id}
    }

This is my api call.

server.js
const axios = require('axios');
const url = process.env.URL;

function getApi(id) {
   return axios.get(url   id).catch(function (error) {
    if (error.response) {
      // Request made and server responded
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }});
}

module.exports = getApi

This is how I tried to test.

    test.js
    jest.mock('./server');
    const axios = require('axios');
    const adapt = require('./adapter');
    
    describe("Adapter Test", () => {
      test("adapt", async () => {
    
        var result = await adapt(getMessage());
        const mockResp = {"data":{"data": {"id":10}}};
        axios.get = jest.fn(() => mockResp);
    
     assert
        expect(result).toStrictEqual(getOfferMessage());
      });
    })
    
    function getMessage() {
    return {"content":"{\"id\":10}"};
}

This is my first test in js, and I don't know how to mock the api call.

All I get is "undefined".

Could you help me?

Thanks

CodePudding user response:

You should pass a factory function to jest.mock when mocking your server module

const mockResp = {"data":{"data": {"id":10}}};
jest.mock('./server', () => () => mockResp);
const adapt = require('./adapter');

describe("Adapter Test", () => {
    test("adapt", async () => {
        const result = await adapt(getMessage());
        expect(result).toStrictEqual({ id: 10 });
    });
})

function getMessage() {
    return {"content":"{\"id\":10}"};
}
  • Related