0

I am new to Node and Jest, I am writing test cases to test my API written in Node. I am using Supertest for testing API and Jest for mocking.

Issue: Mocked function is working while inside the test case, however not working when being called through Supertest. Not working means that actual function is being called.

Below is code:

wishlistsController.js

const {getWishlists} = require("../services/wishlist.service")

const index = async (req, res) => {
    const wishlists = await getWishlists(req.body)
    if(req.headers["content-type"] == 'application/json'){
        res.json(wishlists)
    }
    else{
        res.render("wishlists/index", {wishlists: wishlists})
    }
}

module.exports = {index}

wishlist.service.js

const Wishlist = require("../models/Wishlist")

const getWishlists = async (requestData) => {
    const wishlists = await Wishlist.find().exec()
    return wishlists
}

module.exports = {getWishlists}

Wishlist.test.js

const supertest = require("supertest")
const WishlistService = require("../services/wishlist.service")
const {app} = require('../index.js')

describe("Testing Wishlist Apis ", () => {
    it("should return 200 for wishlists fetch", async () => {

        payload = "Some Mock Value"

        const getWishlistsMock = jest.spyOn(WishlistService, "getWishlists")
        getWishlistsMock.mockImplementation(() => payload);

        console.log("==calling mock==",WishlistService.getWishlists()) // logs "Some Mock Value"
        const { statusCode, body } = await supertest(app)
          .get("/wishlists")
          .set('Content-Type',  'application/json')
          .send();

    console.log("== response ==", body) // returns value from actual function
        expect(body).toEqual(payload); // Test FAILS
        expect(statusCode).toBe(200) // Passes

    })
})

As seen above, the test case fails because mocked value is not returned. What am I missing? Please help fix this.

wayne
  • 393
  • 2
  • 13
  • check [this](https://stackoverflow.com/questions/45111198/how-to-mock-functions-in-the-same-module-using-jest) link to see if it addresses your issue. And [this](https://12ft.io/proxy?q=https%3A%2F%2Fmedium.com%2F%40DavideRama%2Fmock-spy-exported-functions-within-a-single-module-in-jest-cdf2b61af642) for a possible explanation. – Nazrul Chowdhury Jul 24 '23 at 12:49
  • @NazrulChowdhury in the link shared, it has self defined mock functions which are called by self defined functions. I have tried this part, it works for me as well. However, Above problem is when supertest is in use, and it doesn't make use of the Mock function rather calls the actual function itself – wayne Jul 24 '23 at 13:44

1 Answers1

1

Try this approach, it should work

const supertest = require("supertest")
const {app} = require('../index.js')
const WishlistService = require("../services/wishlist.service")

// Mock the module here....
jest.mock("../services/wishlist.service")

describe("Testing Wishlist Apis ", () => {
    it("should return 200 for wishlists fetch", async () => {

        payload = "Some Mock Value"

        // Set up the mock implementation
        WishlistService.getWishlists.mockImplementation(() => payload);

        //supertest call here... 

        // assertions here...

    })
})
Nazrul Chowdhury
  • 1,483
  • 1
  • 5
  • 11
  • This worked. Please also explain why did my code not work and how did this work? – wayne Jul 25 '23 at 16:31
  • @wayne It looks like a good topic to ask SO about. Maybe you can raise this question? – Nazrul Chowdhury Jul 25 '23 at 19:23
  • It was obvious that spyOn was failing to target the correct functions reference, because the original function was still being triggered. So I just tried a different approach for targeting the function. – Nazrul Chowdhury Jul 25 '23 at 19:40
  • okay. But it was not failing in the tutorial I checked. Anway, Thanks a bunch – wayne Jul 26 '23 at 01:42