How can I get Jest to transpile node_modules/@nativescript/core properly? Jest + NativeScript + Angular + Nx

Viewed 705

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.

2 Answers

I am using Nativescript-vue and I got the same error with you. I found a solution but I do not know does it work to you.

do not use import Vue from "nativescript-vue"; in your .vue file. try import { Vue } from "vue-property-decorator"; You will got some compile error when you want to use something in "nativescript-vue" and not in "vue-property-decorator". You can add extend/vue-extend.ts file to add interface, then the compile error will gone. The vue-extend.ts will like this below.

import { Vue } from "vue-property-decorator";
declare module "vue-property-decorator" {
  interface Vue {
    $navigateTo(args: any): any;
    $navigateTo(args: any, {}): any;
    $navigateBack(): any;
  }
}

This working for me:

  • npm i jest -D
  • npm i @babel/preset-env -D
  • npm i @types/jest -D
  • npm i babel-preset-env -D
  • npm i @vue/test-utils vue-jest babel-jest -D
  • npm i --save-dev @vue/vue2-jest
//jest.config.js

module.exports = {
  verbose: true,
  moduleFileExtensions: ["ts", "js", "json", "vue"],
  transform: {
    ".*\\.(vue)$": "@vue/vue2-jest",
    "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
    "^.+\\.tsx?$": "ts-jest",
  },
  moduleNameMapper: {
    "^@/(.*)": "<rootDir>/app/$1",

    "^~/(.*)": "<rootDir>/app/$1",
  },
  roots: ["<rootDir>/tests/"],
  testEnvironment: "jsdom",
  setupFiles: ["<rootDir>/tests/setup.ts"],
};

//setup.ts
import Vue from "vue";
import { config } from "@vue/test-utils";

jest.mock("nativescript-vue", () => Vue);

const NSElements = [
  "ActionBar",
  "ActionItem",
  "FormattedString",
  "GridLayout",
  "HtmlView",
  "NavigationButton",
  "Page",
  "StackLayout",
  "AbsoluteLayout",
  "FlexboxLayout",
  "TabView",
  "TabViewItem",
  "TextField",
];
NSElements.forEach((ele) => {
  Vue.config.ignoredElements.push(ele);
});

//.babelrc

{
  "presets": [
    ["env", { "modules": false }]

  ],
  "env": {
    "test": {
      "presets": [
        ["env", { "targets": { "node": "current" }}]
      ]
    }
  }
}

//tsconfig.json
....
"types": ["jest","node"],
"include": ["app", "types"],
"typeRoots": ["types"], //REMOVE THIS LINE
....

And then:

// Component.test.ts
import { shallowMount } from "@vue/test-utils";
import Component from "../../app/components/Component.vue";

let wrapper: any;

beforeEach(() => {
  wrapper = shallowMount(Component, {
    propsData: { text: "aBC" },
    mocks: {},
    stubs: {},
    methods: {},
  });
});

afterEach(() => {
  wrapper.destroy();
});

describe("Component", () => {
  it("is a Vue instance", () => {
    expect(wrapper.isVueInstance).toBeTruthy();
  });

  it("ComputedProp", () => {
    expect(wrapper.vm.computedProp).toBe("valueExpeted");
  });
});

Related