I am trying to write unit tests for the payment service. the payment module as follows:
src/modules/payment
├── __mocks__
│ └── payment.service.js
├── payment.controller.js
├── payment.routes.js
├── payment.service.js
└── payment.test.js
here is the package.json :
// package.json
"scripts": {
"test": "NODE_ENV=test NODE_OPTIONS=--experimental-vm-modules npx jest --forceExit --maxWorkers=1 \"src/modules/*/.*\\*.test\\.js\"",
}
"type": "module",
"jest": {
"testEnvironment": "node",
"verbose": true,
"setupFilesAfterEnv": [
"<rootDir>/src/config/tests/global-test.js"
],
"transform" : {}
},
the test workflow is very simple :
// payment.service.js
export default {
getModuleName: () => "real_data"
}
// __mocks__/payment.service.js
export default {
getModuleName: () => "test_data"
}
// the test
import {jest} from '@jest/globals'
import paymentService from './payment.service'
jest.mock('./payment.service')
describe("Payment unit tests : ", () => {
it("should return the mock name", () => {
const name = paymentService.getModuleName()
expect(name).toBe("test_data")
})
})
I tried doing like this : https://stackoverflow.com/a/49694590/16787671
jest.mock('./payment.service', () => ({ __esModule: true, default: { getModuleName: jest.fn() }}))
but I failed since I am using nodejs module, I also followed the jest ECMAScript Modules guide from here : https://jestjs.io/docs/ecmascript-modules