I'm having trouble mocking specific functions within my modules using commonjs
example module db.js
function createDefaultProfile(user_id) {
return { version: 1, username: user_id };
}
function updateOrCreateProfile(user_id, profile) {
if (profile && profile.credential_id) return null; //no need to update
if (!profile) profile = createDefaultProfile(user_id);
if (!profile.credential_id) {
//update profile with key
}
module.exports = {createDefaultProfile, updateOrCreateProfile }
example test file try 1:
describe("updateOrCreateUser()", () => {
const db = require('../db.js')
it("should call createDefaultProfile() when no profile is provided", () => {
db.createDefaultProfile = jest.fn()
db.updateOrCreateProfile(userID)
expect(db.createDefaultProfile).toHaveBeenCalledTimes(1)
})
})
example test file try 2:
describe("updateOrCreateUser()", () => {
jest.mock('../db', () => {
// Require the original module to not be mocked...
const originalModule = jest.requireActual('../db');
return {
__esModule: true, // Use it when dealing with esModules
...originalModule,
createDefaultProfile: jest.fn().mockReturnValue('arbitrary value'),
}
})
const db = require('../db.js')
it("should call createDefaultProfile() when no profile is provided", () => {
db.updateOrCreateProfile(userID)
expect(db.createDefaultProfile).toHaveBeenCalledTimes(1)
})
})
both return the wrong values as the mocked module never gets called.. in both instances it seems as if the scope of the mocked module is not correct...
Aucun commentaire:
Enregistrer un commentaire