Problem description
When testing a service in an API used in a Next.js app and using Babel Jest for specific test files, I'm encountering an issue regarding locating a module. The error that appears in the terminal is shown below.
Cannot find module '#node-web-compat' from 'node_modules/aws-jwt-verify/dist/cjs/https.js'
Require stack:
node_modules/aws-jwt-verify/dist/cjs/https.js
node_modules/aws-jwt-verify/dist/cjs/jwk.js
node_modules/aws-jwt-verify/dist/cjs/jwt-rsa.js
node_modules/aws-jwt-verify/dist/cjs/index.js
pages/api/auth/auth.service.ts
__tests__/sign-up/api/auth/auth-service.test.ts
at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:491:11)
at Object.<anonymous> (node_modules/aws-jwt-verify/dist/cjs/https.js:9:28)
The service being tested is utilized by TypeScript decorator in middleware. It functions correctly during manual testing but encounters issues only when running tests.
Objective
The goal is to unit test a service that utilizes the library aws-jwt-verify
to verify JWT access tokens. The aim is to mock it and use it in Jest unit tests.
Tried methods
I attempted copying the dependency to devDependencies
and reinstalling packages, but this did not resolve the issue.
Dependencies in package.json
{
...
"dependencies": {
"@aws-sdk/client-cognito-identity-provider": "^3.137.0",
"@chakra-ui/react": "^2.2.3",
...
}
...
}
tsconfig.json
{
"compilerOptions": {
"target": "es5",
...
},
...
}
jest.config.js
const nextJest = require('next/jest');
const createJestConfig = nextJest({
dir: './'
});
const customJestConfig = {
moduleDirectories: ['node_modules', '<rootDir>/']
};
module.exports = createJestConfig(customJestConfig);
auth.service.ts
// Code for auth.service.ts goes here
auth-service.test.ts
// Code for auth-service.test.ts goes here