I am currently attempting to setup a multiplatform codesharing starter project using the Nx monorepo tool. This project uses Angular for the web, and NativeScript for crossplatform mobile.
Ideally I would like to be able to use Jest to run all unit tests. Currently, I am able to successfully run unit tests using jest from the root directory. They execute properly for the Angular app and it's libraries, but I am encountering errors when attempting to execute unit tests for the NativeScript (NativeScript Angular) project, specifically when those unit tests import NativeScript components (i.e. are actually useful). That is, dummy tests expecting true to be true work fine, so Jest is finding and running the tests with no problem. But when I try to import the components, I have issues.
I have worked the problem some. Initially the error I was getting:
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/home/james/WebstormProjects/please-remind.me/apps/mobile/node_modules/@nativescript/core/index.js:3
import './globals';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1350:14)
at node_modules/@nativescript/angular/bundles/nativescript-angular.umd.js:2:85
at Object.<anonymous> (node_modules/@nativescript/angular/bundles/nativescript-angular.umd.js:5:2)
So I followed the instructions and visited the Jest website where I was instructed to make the following change to my jest.config.js:
module.exports = {
displayName: 'mobile',
preset: '../../jest.preset.js',
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
globals: {
'ts-jest': {
tsConfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$',
astTransformers: {
before: [
'jest-preset-angular/build/InlineFilesTransformer',
'jest-preset-angular/build/StripStylesTransformer',
],
},
},
},
coverageDirectory: '../../coverage/apps/mobile',
snapshotSerializers: [
'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js',
'jest-preset-angular/build/AngularSnapshotSerializer.js',
'jest-preset-angular/build/HTMLCommentSerializer.js',
],
transformIgnorePatterns: [ <<<<<<< Added
'../../node_modules/(?!(@nativescript)/)' <<<<<<< Added
] <<<<<<< Added
};
It should be noted I copied this jest.config.js from the web project which is how it is automatically generated.
So I have a very simple unit test app.component.spec.ts which attempts to import the AppComponent:
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [AppComponent],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
});
Now the error is:
● Test suite failed to run
Cannot find module './application' from 'node_modules/@nativescript/core/index.js'
Require stack:
node_modules/@nativescript/core/index.js
node_modules/@nativescript/angular/bundles/nativescript-angular.umd.js
src/app/app.component.ts
src/app/app.component.spec.ts
at Resolver.resolveModule (../../node_modules/jest-resolve/build/index.js:306:11)
at Object.<anonymous> (node_modules/@nativescript/core/index.js:4:1)
console.log
Profiling startup failed to figure out defaults from package.json, error: Error: Cannot find module '~/package.json' from 'node_modules/@nativescript/core/profiling/index.js'
at Object.<anonymous> (node_modules/@nativescript/core/profiling/index.js:134:17)
I have tried adding the testEnvironment: "node", to my jest.config.js:
module.exports = {
displayName: 'mobile',
preset: '../../jest.preset.js',
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
globals: {
'ts-jest': {
tsConfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$',
astTransformers: {
before: [
'jest-preset-angular/build/InlineFilesTransformer',
'jest-preset-angular/build/StripStylesTransformer',
],
},
},
},
coverageDirectory: '../../coverage/apps/mobile',
snapshotSerializers: [
'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js',
'jest-preset-angular/build/AngularSnapshotSerializer.js',
'jest-preset-angular/build/HTMLCommentSerializer.js',
],
transformIgnorePatterns: [ <<<<<<< Added
'../../node_modules/(?!(@nativescript)/)' <<<<<<< Added
] <<<<<<< Added
testEnvironment: "node" <<<<<<< Added
};
And a different error appears:
● Test suite failed to run
Cannot find module '../timer' from 'node_modules/@nativescript/core/globals/index.js'
at Resolver.resolveModule (../../node_modules/jest-resolve/build/index.js:306:11)
at Object.loader (node_modules/@nativescript/core/globals/index.js:256:46)
at loadModule (node_modules/@nativescript/core/globals/index.js:203:43)
at Object.get [as clearInterval] (node_modules/@nativescript/core/globals/index.js:9:30)
console.log
Profiling startup failed to figure out defaults from package.json, error: Error: Cannot find module '~/package.json' from 'node_modules/@nativescript/core/profiling/index.js'
at Object.<anonymous> (node_modules/@nativescript/core/profiling/index.js:134:17)
So there is definately something involved with ts-jest and it's sort of "just in time" transpilation. I am thinking there a flag I need to set in either my tsconfig.spec.json:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"module": "commonjs",
"allowJs": true,
"types": ["jest", "node"]
},
"files": ["src/test-setup.ts"],
"include": ["**/*.spec.ts", "**/*.d.ts"]
}
Here is the base tsconfig.json that the above is extending:
{
"compilerOptions": {
"module": "esnext",
"target": "es2017",
"moduleResolution": "node",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"noEmitHelpers": true,
"noEmitOnError": true,
"skipLibCheck": true,
"lib": [
"es2017",
"dom"
],
"baseUrl": ".",
"paths": {
"~/*": [
"src/*"
]
}
},
"exclude": [
"node_modules",
"platforms"
]
}
Thanks in advance.