I have react/nextjs/MUI app.
I need to have 2 different independent instances of the same module using the same codebase and for this purpose I use the cool hack that works fine:
in all files
where I need the first instance I use:
import API from 'src/api';
also I have a separate file that allows me to create another instance:
import API from 'src/api?service';
const SERVICESAPI = API
SERVICESAPI.changeBaseURL(process.env.NEXT_PUBLIC_SERVICES_API_URL)
export default SERVICESAPI;
so everywhere where I need this second instance I use
import SERVICESAPI from 'src/serviceapi';
this works 100% properly without any bugs
However this does not work with react testing library and jest.
the API can be mocked successfully:
jest.mock('src/api');
But when I try to mock the SERVICEAPI
jest.mock('src/serviceapi');
I get this error:
Configuration error:
Could not locate module src/serviceapi mapped as:
c:myprojecsrc$1.
Please check your configuration for these entries:
{
"moduleNameMapper": {
"/^src/(.*)$/": "c:myprojectsrc$1"
},
"resolver": undefined
}
13 | LicenseInfo.setLicenseKey('123');
14 | jest.mock('src/api');
> 15 | jest.mock('src/serviceapi');
| ^
16 | jest.mock('src/components/commonUI/DataGridProWrapper');
17 |
at createNoMappedModuleFoundError (node_modules/jest-resolve/build/resolver.js:579:17)
at Object.<anonymous> (src/setupTests.js:15:6)
at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/@jest/core/build/runJest.js:404:19)
Also I made experiments with simplier examples and I got the same results: jest does not recognize import with “?” signs.
Is there any way to make jest work with “?” imports?