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.