'rxjs' module not found while running Jest test suite - jestjs

I have a Nest JS application for which I am writing tests for some of the Provider classes. The beforeAll fn. of jest defined in my *.spec.ts file runs fine but the jest todo() fn. fails with the following error:
Cannot find module 'rxjs' from 'node_modules/#nestjs/common/cache/interceptors/cache.interceptor.js'
Require stack:
node_modules/#nestjs/common/cache/interceptors/cache.interceptor.js
node_modules/#nestjs/common/cache/interceptors/index.js
node_modules/#nestjs/common/cache/index.js
node_modules/#nestjs/common/index.js
node_modules/#nestjs/testing/testing-module.builder.js
node_modules/#nestjs/testing/test.js
node_modules/#nestjs/testing/index.js
src/bookmark/test/integration/bkm.service.int-spec.ts
at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:491:11)
at Object.<anonymous> (node_modules/#nestjs/common/cache/interceptors/cache.interceptor.js:5:16)
My package.json has rxjs defined in the "dependencies" section with a version of ^7.2.0.
My test in the *.spec.ts testing class looks like this:
describe('BookmarkService Integration', () => {
let prisma: PrismaService;
let bookmarkService: BookmarkService
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [AppModule],
}).compile();
prisma = moduleRef.get(PrismaService);
bookmarkService = moduleRef.get(BookmarkService);
await prisma.cleanDatabase();
});
it.todo('Default test pass')
})
I have not tried explicitly doing a npm install of rxjs since I don't understand the consequence of installing it when it already came as a default dependency when I initialized my Nest application. Any help would be greatly appreciated.
Thanks

Cannot find module is a common error that is thrown when a dependency requested by your project code or by one of the imported modules cannot find the target module inside the node_module directory.
This issue can be caused by a multitude of scenarios, but going by your response to my comment, it was likely caused by the fact that npm had cached the package-lock.json properties and upon rerunning npm install would still add incorrect modules to the node_modules directory. Hence the resolution is a simple deletion of the node_modules directory, the package-lock.json file and the rerunning of the npm install command.
To answer your question on how this was still a problem even when package-lock.json did contain the rxjs library reference, there could have been a number of scenarios that I would have to speculate; for one, what you were inspecting could have been a transitive rxjs dependency which is being used by another library and is not the rxjs library that is actually being requested for in the error. Alternatively, there is a chance that even though rxjs was defined in the package-lock.json file, it may not have actually been present in the node_modules directory as it may have failed to install. This really depends on the exact sequence of things that you have done prior to seeing the issue, but I hope my explanation clarifies the problem you were facing.

Related

export '__RouterContext' (imported as 's') was not found in 'react-router'

This is my error and I can't fix it :(((
This error appeared while I
import { GuardProvider, GuardedRoute } from 'react-router-guards'
and use it.
It's not expressly limited by react-router-guard's package.json the repo and README both state there's a peer dependency on react-router-dom#5.
See Requirements.
This package has the following peer dependencies:
React v16.8.0+ (for hooks ⚓️)
React Router DOM v5.0.0+
Based on the error it seems you have react-router-dom#6 installed and it has many different exports than the previous version. To resolve you will need to revert to the v5 version of react-router-dom.
To install, run from the project's root directory:
npm i -s react-router-dom#5

Publish Typescript Interfaces with NPM

I'm working in a project that has multiple typescript projects. I'm trying to have a common package for all the interfaces, types, enums, etc.
I thought I could make it work creating a NPM package with Typescript and have an index.ts with this content:
When I'm working in the projects that depend on this package, everything seems fine, but when I want to start the development environment I'm getting this error:
I've got the suggestion of running ts-node with --skipIgnore flag, but I'm getting the same error:
Maybe I needed to compile the code and import the .js (doesn't make ANY sense, but at this point 🤷🏽‍♂️)... no luck.
Let me share both tsconfig.json:
The one from the "common" package:
The one from the project that depends on the common package:
Things suggested and tried:
Because your target is ES6, commonjs modules cannot use your package. The dependent project should change its module type to ES6 as well - #kellys
Changing project's module to ES6, brings me this error:
All right, let's add moduleResolution: "node" ... and I'm getting:
So I'm adding "type":"module" in package.json:

Nodejs: Cannot find module `nanoid`

When I try to compile my Typescript project (NestJS) I came across the following problem.
Some packages like nanoid, cookie-parser give error Error: Cannot find module 'nanoid'
The code where they used is below:
...
import { nanoid } from "nanoid";
...
const confirmToken = nanoid(32);
...
Here are what I tried:
I checked the node_modules directory. The package is there
Tried to completely remove node_modules and package.json.lock.
Used v16.14.0, v17 versions of NodeJS
Used yarn and npm
None of these ways helped.
Again, this error happens with only certain packages.
What could be an issue?

React testing: "TypeError: MutationObserver is not a constructor"

The Problem
I'm trying to test a new release of an internal component library, which recently upgraded some dependencies and now uses Jest 26 internally. That library also exports some testing helpers.
In another codebase that utilizes the aforementioned component library, I'm getting the following when running certain unit tests:
TypeError: MutationObserver is not a constructor
at /<path_to_repo>/node_modules/#testing-library/dom/dist/wait-for.js:78:18
This may or may not be related to the fact that the testing helpers exported by the component library relied on Jest 26. (It's hard to tell if these helpers are being used -- we've got some very big "unit" tests.)
Relevant package versions (in the consuming codebase):
react-scripts 3.4.4
Jest 24.9.0
testing-library/dom 7.26.3
testing-library/jest-dom 5.10.0
testing-library/react ^10.0.0
Running yarn list jsdom yields the following:
├─ jest-environment-jsdom-fourteen#1.0.1
│ └─ jsdom#14.1.0
├─ jest-environment-jsdom#24.9.0
│ └─ jsdom#11.12.0
└─ jsdom#16.4.0
I know that upgrading react-scripts and Jest would likely fix this issue, but I'm trying to find a way that doesn't involve that. (We ideally don't want this to be a prerequisite for upgrading to our new component library version.)
Attempted Solutions
Forcing a Newer jsdom
First I tried adding
"resolutions": {
"jsdom": "^14.0.0"
},
to my package.json. This did make yarn list jsdom output only jsdom#14.1.0, but I still got the same TypeError. Resolving to ^15.0.0 resulted in the same error, and resolving to ^16.0.0 gave me the following error:
TypeError: this.dom.runVMScript is not a function
at JSDOMEnvironment.runScript (node_modules/jest-environment-jsdom/build/index.js:187:23)
Using jest-environment-jsdom-*
I tried following this thread by installing jest-environment-jsom-sixteen. Altering my test script in package.json and running yarn test --showConfig yields a bunch of info including the following line:
"testEnvironment": "/<path_to_repo>/node_modules/jest-environment-jsdom-sixteen/lib/index.js",
If I add a console.log(navigator.userAgent) to my test, I also get
Mozilla/5.0 (darwin) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/16.4.0
However, I still get the same TypeError: MutationObserver is not a constructor.
I also tried jest-environment-jsdom-fourteen and jest-environment-jsdom-fifteen, and tried while forcing jsdom to ^14.0.0. Same result.
Using mutationobserver-shim
I ran yarn add -D mutationobserver-shim and imported it (with import 'mutationobserver-shim') in my jestSetup.ts (which is what globalSetup in my Jest configuration points to), but that resulted in the following error:
ReferenceError: window is not defined
at Object.<anonymous> (/<path_to_repo>/node_modules/mutationobserver-shim/dist/mutationobserver.min.js:12:1)
Adding the import instead to my test file yielded the same TypeError as above, and adding a console.log(global.MutationObserver) to my test file yielded undefined.
A Not-So-Great Solution
After a lot of trial and error, I discovered that if I 1) have jest-environment-jsdom-sixteen installed and tell Jest to use it and 2) add import 'mutationobserver-shim' in my test file, and the tests will pass. However, if I put add the import to my Jest globalSetup file, it doesn't work. I get the same ReferenceError: window is not defined error as before.
My Question
How can I get rid of both errors without requiring users of our component library to add an import statement to all of their test files?
A polyfill should be applied in setupFilesAfterEnv, because this is where the jsdom environment is instantiated and window becomes available. window isn't supposed to be available in globalSetup because it doesn't run in a test scope.
In case this is an unejected create-react-app project, the setup file that corresponds to setupFilesAfterEnv is src/setupTests.ts (src/setupTests.js).
That the newer jsdom version causes an error means it's incompatible with the old Jest version (24). They should be ejected and upgraded, or newer CRA (react-scripts#4) with Jest 26 support has to be used.

"Cannot find module" when running unit tests on node.js with react as peer dependency in common package

I have following app structure:
Application A
Application B
Common package
Now Application A and B have in package.json the common package added:
{
dependencies: {
"commonPackage": "file:../../../commonPackage"
}
}
both apps use React, as well as the common package, all had React added with npm, and it worked, before we started to use react hooks.
Because when we started, we got an Invalid Hook Call Warning due to having "more than one copy of React", so to avoid that, in the common package, the react dependency was moved to peerDependencies so that the react instance from the app is used and not from the package.
It works great in the browser when we run both apps A and B, but when I run my mocha tests in the console, I get:
ERROR in ../commonPackage/~/#uifabric/utilities/lib/customizations/Customizer.js
Module not found: Error: Can't resolve 'react' in 'D:\myProject\commonPackage\node_modules\#uifabric\utilities\lib\customizations'
this is from the office-ui-fabric-react package we use, but it seems like a more general issue with dependency resolution.
Project is in TypeScript, we use webpack for the compilation of the app for the browser, and tsc to compile for the unit tests.
I found some answers, suggesting to npm link react in the common package to the react package in the application node_modules, but it seems wrong, since the common package is used by two applications, it would solve the issue only for one.
In the case above we finally came to a solution which was
adding back react as devDependency to Common package
using esm package to help our test runs understand es6 module export/import that came with fabric package. Just using mocha --require esm ...
ejecting and adding alias to webpack.config.js in Application
alias: {
'react': path.resolve('./node_modules/react')
}
Application A, B and hooks work now.

Resources