-1

Hi have an simple express application with below structure which tries to call a 3rd party url to get some information. To test the code, I am using jest test framework and would like to know how can I mock the axios calls to 3rd party url.

File structure

controllers
  -> controller.js
routes
  -> route.js
tests
  -> test.js
server.js

Code

server.js

const express = require('express');
const cors = require('cors');
const testRoutes = require("./routes/route.js");

const app = express();
app.use(cors());

app.use("/", testRoutes);

const port = process.env.PORT || 3000;
var server = app.listen(port, function () {
    let host = server.address().address;
    let port = server.address().port;
    console.log("Example app listening at : http://%s:%s", host, port);
});

module.exports = app;

route.js

const express = require("express");
const router = express.Router();

const {
    getUser
} = require("../controllers/controller");

// Endpoint for fetching userid and its role
router.get('/user', getUser);

module.exports = router;

controller.js

const axios = require('axios');

const baseUrl= "Some 3rd party url"

// Function for fetching userid and its role
const getUser = async (req, res) => {
    let url = baseUrl + '/user';
    axios.get(url)
        .then((response) => {
            res.send(response.data).status(200);
        })
        .catch((error) => {
            console.log(error);
        });
};

module.exports = {
    getUser
}

I tried writing a unit test case using jest framework and mocked the axios call to the 3rd party url as below.

test.js

const axios = require('axios');
const supertest = require('supertest');
const app = require('../server');
const request = supertest(app);

jest.mock("axios");
const baseUrl= "Some 3rd party url"

// Test endpoint for fetching userid and its role
describe("GET /user", () => {
    it("should return a user", async () => {
        // Given
        const users = {
            id: "1234567",
            role: "Test"
        };
        axios.get.mockResolvedValueOnce(users);

        // When
        const res = await request.get('/user');

        // Then
        expect(axios.get).toHaveBeenCalledWith(`${baseUrl}/user`);
        expect(res.statusCode).toBe(200);
        expect(res.id).toBe("1234567");
        expect(res.role).toBe("Test");
    });
});

I was expecting the url to be mocked and my endpoint get('/user') to fetch the mocked values for 'id' and 'role'.

However it did not work.

1 Answers1

0

The issue got resolved. In controller.js in method getUser, I was passing "response.data" and while mocking property "data" did not exist. Hence updated the mock data as below

const users = { data: { id: "1234567", role: "Test" } };