Why decorators won't work in Jest with Babel? - jestjs

I'm trying to get JavaScript decorators to work using Jest and Babel:
./package.json
[...]
"devDependencies": {
[...]
"#babel/core": "7.2.2",
"#babel/plugin-proposal-class-properties": "^7.3.0",
"#babel/plugin-proposal-decorators": "^7.3.0",
"#babel/preset-env": "^7.3.1",
[...]
"jest": "^24.1.0"
},
[...]
"scripts": {
[...]
"jest --no-cache --verbose --config ./test/unit/jest.json"
}
./test/unit/.babelrc
{
"presets": [
[
"#babel/preset-env", {
"targets": {
"node": "current"
},
"modules": "commonjs",
"loose": true,
"debug": true
}
]
],
"plugins": [
["#babel/plugin-proposal-decorators", { "legacy": true }],
["#babel/plugin-proposal-class-properties", { "loose": true}]
]
}
./test/unit/jest.json
{
"modulePaths": [
"<rootDir>/../../src",
"<rootDir>/../../node_modules"
],
"moduleFileExtensions": [
"js",
"json"
],
"testRegex": "\\.spec\\.js$",
"setupFiles": [
"<rootDir>/jest.js"
],
"testEnvironment": "node"
}
./test/unit/jest.js
import 'aurelia-polyfills';
import {Options} from 'aurelia-loader-nodejs';
import {globalize} from 'aurelia-pal-nodejs';
import * as path from 'path';
Options.relativeToDir = path.join(__dirname, '../../src');
globalize();
When I run yarn test I get:
yarn run v1.12.3
$ jest --no-cache --verbose --config ./test/unit/jest.json
#babel/preset-env: `DEBUG` option
Using targets:
{
"node": "11.9"
}
Using modules transform: commonjs
Using plugins:
syntax-async-generators { "node":"11.9" }
syntax-object-rest-spread { "node":"11.9" }
syntax-json-strings { "node":"11.9" }
syntax-optional-catch-binding { "node":"11.9" }
Using polyfills: No polyfills were added, since the `useBuiltIns` option was not set.
console.error internal/process/next_tick.js:81
{ SyntaxError: [...]/src/resources/elements/product/price.js: Support for the experimental syntax 'decorators-legacy' isn't currently enabled (10:1):
8 | import { DataService } from 'services';
9 |
> 10 | #inject(Element, Store, DataService, EventAggregator, I18N)
| ^
11 | #useViewStrategy(new RemoteViewStrategy())
12 | export class ProductPrice {
13 |
at Parser.raise ([...]/node_modules/#babel/parser/lib/index.js:3831:17)
at Parser.expectOnePlugin ([...]/node_modules/#babel/parser/lib/index.js:5158:18)
at Parser.parseDecorator ([...]/node_modules/#babel/parser/lib/index.js:7428:10)
at Parser.parseDecorators ([...]/node_modules/#babel/parser/lib/index.js:7410:30)
at Parser.parseStatement ([...]/node_modules/#babel/parser/lib/index.js:7245:12)
at Parser.parseBlockOrModuleBlockBody ([...]/node_modules/#babel/parser/lib/index.js:7812:25)
at Parser.parseBlockBody ([...]/node_modules/#babel/parser/lib/index.js:7799:10)
at Parser.parseTopLevel ([...]/node_modules/#babel/parser/lib/index.js:7181:10)
at Parser.parse ([...]/node_modules/#babel/parser/lib/index.js:8660:17)
at parse ([...]/node_modules/#babel/parser/lib/index.js:10643:38)
pos: 362,
loc: Position { line: 10, column: 0 },
missingPlugin: [ 'decorators-legacy', 'decorators' ],
code: 'BABEL_PARSE_ERROR' }
console.log test/unit/resources/elements/price.spec.js:25
SyntaxError: [...]/src/resources/elements/product/price.js: Support for the experimental syntax 'decorators-legacy' isn't currently enabled (10:1):
8 | import { DataService } from 'services';
9 |
> 10 | #inject(Element, Store, DataService, EventAggregator, I18N)
| ^
11 | #useViewStrategy(new RemoteViewStrategy())
12 | export class ProductPrice {
13 |
FAIL test/unit/resources/elements/price.spec.js (5.467s)
ProductPrice
✕ should render current (5008ms)
● ProductPrice › should render current
Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
18 | });
19 |
> 20 | it('should render current', done => {
| ^
21 | component.create(bootstrap).then(() => {
22 | const currentElement = document.querySelector('.current');
23 | expect(currentElement.innerHTML).toBe('');
at Spec (../../node_modules/jest-jasmine2/build/jasmine/Spec.js:92:20)
at Suite.it (resources/elements/price.spec.js:20:5)
● ProductPrice › should render current
Cannot call ComponentTester.dispose() before ComponentTester.create()
27 |
28 | afterEach(() => {
> 29 | component.dispose();
| ^
30 | });
31 | });
at ComponentTester.Object.<anonymous>.ComponentTester.dispose (../../node_modules/aurelia-testing/dist/commonjs/component-tester.js:66:19)
at Object.dispose (resources/elements/price.spec.js:29:19)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 6.389s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
What I'm doing wrong?

A good hint comes with the error message:
[...]
missingPlugin: [ 'decorators-legacy', 'decorators' ],
code: 'BABEL_PARSE_ERROR' }
The Babel integration of Jest tooks the .babelrc in the first place, for every other file reached from the test it searched only in the project root. In this case the Babel configuration was in ./test/unit.
So putting .babelrc into the project root folder is one possible fix (but not the best). More approaches can be found here.

Related

vue/cli-plugin-unit-jest cannot find module

I am using vue/cli-plugin-unit-jest and after setting it up accourding to the docs I keep getting this error:
Cannot find module '#antmedia/webrtc_adaptor' from 'src/components/player.vue'
Require stack:
src/components/player.vue
src/components/Dashboard.vue
src/views/Operation.vue
src/router/index.js
src/stores/modules/account.module.js
src/stores/index.js
tests/unit/cameras.spec.js
61 | import config from '../config/config'
62 | import { mapActions, mapState } from 'vuex'
> 63 | import { WebRTCAdaptor } from '#antmedia/webrtc_adaptor'
| ^
64 |
65 | export default {
66 | name: 'player',
at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:324:11)
at Object.<anonymous> (src/components/player.vue:63:1)
at Object.<anonymous> (src/components/Dashboard.vue:18:1)
When I remove line 63 the test begins to pass so obviously there is some issue with jest resolving the path but I can't find a solution.
This is the jest.config.js file:
module.exports = {
verbose: true,
preset: '#vue/cli-plugin-unit-jest',
ResolverOptions: {
paths: [
'<rootDir>/src'
]
}
}
This issue occurs because by default, jest doesn't transform anything from /node_modules.
What worked for me is this:
replace import { WebRTCAdaptor } from '#antmedia/webrtc_adaptor'
with import { WebRTCAdaptor } from '../../node_modules/#antmedia/webrtc_adaptor/src/main/webapp/js/webrtc_adaptor.js'
And in package.json add:
"jest" : {
"preset": "#vue/cli-plugin-unit-jest",
"transformIgnorePatterns": [
"/node_modules/(?!#antmedia).+\\.js$"
]
},
Of course replace #antmedia with the package you want to import.

Gatsby + Jest - How to enable support for the experimental syntax 'jsx'?

Following Gatsby unit test docs:
https://www.gatsbyjs.com/docs/how-to/testing/unit-testing/#writing-tests
I got this error:
Details:
SyntaxError: ../Projects/gatsby/testing-first-steps/src/components/__tests__/header.js: Support for the experimental syntax 'jsx' isn't currently enabled (9:15):
7 | it("renders correctly", () => {
8 | const tree = renderer
> 9 | .create(<Header siteTitle="Default Starter" />)
| ^
10 | .toJSON()
11 | expect(tree).toMatchSnapshot()
12 | })
Add #babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add #babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
Solved! 🤦
https://www.gatsbyjs.com/docs/how-to/custom-configuration/babel/#how-to-use-a-custom-babelrc-file
Add this:
npm install --save-dev babel-preset-gatsby
then in .babelrc file add this:
{
"presets": [
[
"babel-preset-gatsby",
{
"targets": {
"browsers": [">0.25%", "not dead"]
}
}
]
]
}

Jest return error when using "import * as .."

I have problems to run my test suite when I used import * as './filename.js' with Jest.
All the others imports run without problems so I don't think is a problem with babel configuration.
I use Nextjs 10(so react17), Jest, Typescript and babel-jest.
Here is my babel.config.js
{
"env": {
"development": {
"presets": ["next/babel"]
},
"production": {
"presets": ["next/babel"]
},
"test": {
"presets": [
[
"next/babel",
{
"preset-env": {
"modules": "commonjs"
}
}
]
]
}
}
}
And here an example of the test that gives the error:
import React, { FC, useEffect } from 'react'
import Head from 'next/head'
import Header from '../Header/Header'
import HeaderHome from '../HeaderHome/HeaderHome'
import Footer from '../Footer/Footer'
import styles from './Layout.module.css'
import * as settingsHelper from '../../helpers/_settingsHelper'
// .... normal react component here.
And inside the _seetingsHelper.js I call my cookieHelper like so:
import * as cookieHelper from './_cookies'
function initialise () {
// body of function here
}
error:
.../helpers/_settingsHelper.js:2
import * as cookieHelper from './_cookies'
^^^^^^
SyntaxError: Cannot use import statement outside a module
6 | import styles from './Layout.module.css'
7 |
> 8 | import * as settingsHelper from '../../helpers/_settingsHelper'
| ^
9 |
10 | // prettier-ignore
11 | interface LayoutProps {
Someone already encountered this issue?

"Identifier 'global' has already been declared at compileFunction" error In jest tests after upgrading to monaco-editor 0.21.0

I upgraded my react project to use monaco-editor version 0.21.0, since then the jest tests for files where monaco-editor is being imported have started to fail with the following error:
● Test suite failed to run
/Users/omerharoon/Documents/code/packages/webapp/node_modules/monaco-editor/esm/vs/editor/editor.api.js:20
const global = self; // Set defaults for standalone editor
^
SyntaxError: Identifier 'global' has already been declared
at compileFunction (<anonymous>)
2 |
3 | import React from 'react';
> 4 | import * as monaco from 'monaco-editor';
| ^
5 | import { Resizable } from 're-resizable';
6 | import {
7 | getLanguageFromFilename,
at Runtime._execModule (node_modules/jest-runtime/build/index.js:1179:56)
at Object.<anonymous> (src/components/helpers/MonacoEditor/index.tsx:4:1)
at Object.<anonymous> (src/components/helpers/MonacoEditor/monaco_colorization.spec.tsx:6:1)
This started occurring right after the upgrade, the old version was 0.19.3 and all the tests worked fine on that version. monaco-editor-webpack-plugin was also upgraded from 1.9.0 to 2.0.0
We're importing monaco directly from
node_modules/monaco-editor/esm/vs/editor/editor.api
in order to overcome lazy loading issues.
Jest Config:
"jest": {
"modulePaths": [
"<rootDir>/src"
],
"collectCoverageFrom": [
"**/*.{js,jsx,ts,tsx}",
"!**/*.d.ts",
"!**/node_modules/**",
"!**/public/**",
"!**/next.config.js",
"!**/server.js"
],
"setupFilesAfterEnv": [
"<rootDir>/setupTests.js"
],
"testPathIgnorePatterns": [
"<rootDir>/node_modules/",
"<rootDir>/.next/",
"<rootDir>/public/",
"<rootDir>/config/",
"<rootDir>/next.config.js",
"<rootDir>/server.js",
"<rootDir>/build/"
],
"transform": {
"^.+\\.[jt]sx?$": "babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js"
},
"transformIgnorePatterns": [
"/node_modules/(?!monaco-editor)/",
"^.+\\.module\\.(css|sass|scss)$"
],
"moduleNameMapper": {
"^monaco-editor$": "monaco-editor/esm/vs/editor/editor.api",
"^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
},
"coverageReporters": [
"text",
[
"lcov",
{
"projectRoot": "../../"
}
]
]},
Upgrading to monaco-editor 0.23.0resolved the problem for me.

Jest passing tests but --covering option not picking up files

Problem description:
I have written two tests for a typescript class. Those two tests pass so jest successfully retrieves the test files. I then use the --coverage option but it appears jest is not picking the covered files here.
Here is the output I am getting:
api_jester | PASS src/tests/repositories/user.test.ts
api_jester | User Repository
api_jester | ✓ it should return an empty array (18ms)
api_jester | ✓ should successfully create a user and return its data (7ms)
api_jester |
api_jester | ----------|----------|----------|----------|----------|-------------------|
api_jester | File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
api_jester | ----------|----------|----------|----------|----------|-------------------|
api_jester | All files | 0 | 0 | 0 | 0 | |
api_jester | ----------|----------|----------|----------|----------|-------------------|
api_jester | Test Suites: 1 passed, 1 total
api_jester | Tests: 2 passed, 2 total
api_jester | Snapshots: 0 total
api_jester | Time: 3.208s
api_jester | Ran all test suites.
I have tried playing with the collectCoverageFrom option but without any success. I have tested covering with some simple examples found on github and those were working so the problem is not from my environment. I am guessing I somehow missed something in my configuration but I have spend so much time on this I am getting kind of frustrated so maybe some fresh looks could help..
Project architecture :
config
|__ jest.config.js
|__ tsconfig.json
src
|__tests
| |__repositories
| |__user.test.ts
|__repositories
|___ userRepository
|__User.ts
Jest.config.js :
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
roots: ["../src/tests/"],
transform: {
"^.+\\.tsx?$": "ts-jest"
},
collectCoverageFrom: ["../src/"],
moduleFileExtensions: ["ts", "js", "json"],
coverageDirectory: "../coverage"
};
package.json
{
"name": "theralog_api",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"build": "tsc",
"prettier": "npx prettier --write src/**/*.ts --config ./config/.prettierrc",
"eslint": "npx eslint --config ./config/.eslintrc ./src/**/**/*",
"start:dev": "npx nodemon -L --config ./config/api.nodemon.json",
"test:watch": "npx nodemon -L --config ./config/jester.nodemon.json",
"test:coverage": "npx jest --config ./config/jest.config.js --coverage --colors --watch"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#types/compression": "^1.0.1",
"#types/express": "^4.17.1",
"#types/graphql-depth-limit": "^1.1.2",
"#types/jest": "^24.0.23",
"#types/node": "^12.7.12",
"#typescript-eslint/eslint-plugin": "^2.5.0",
"#typescript-eslint/parser": "^2.5.0",
"apollo-server-testing": "2.9.7",
"babel-jest": "^24.9.0",
"eslint": "^6.5.1",
"eslint-config-prettier": "^6.4.0",
"graphql-depth-limit": "^1.1.0",
"graphql-import": "^0.7.1",
"graphql-import-node": "0.0.4",
"jest": "^24.9.0",
"nodemon": "^1.19.3",
"prettier": "^1.18.2",
"ts-jest": "^24.1.0",
"ts-node": "^8.4.1",
"tsconfig-paths": "^3.9.0",
"typescript": "^3.7.2"
},
"dependencies": {
"apollo-server-express": "^2.9.6",
"compression": "^1.7.4",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"graphql": "^14.5.8",
"http": "0.0.0",
"lodash": "^4.17.15",
"ncp": "^2.0.0",
"pg": "^7.12.1",
"winston": "3.2.1"
}
}
jester.nodemon.json
{
"watch": ["../src"],
"ext": "ts",
"exec": "npx jest --config ./config/jest.config.js --watchAll"
}
You are missing a setting in the jest.config.js, collectCoverage: true
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
roots: ["../src/tests/"],
transform: {
"^.+\\.tsx?$": "ts-jest"
},
collectCoverage: true,
collectCoverageFrom: ["../src/"],
moduleFileExtensions: ["ts", "js", "json"],
coverageDirectory: "../coverage"
};
I also use a more descriptive collectCoverageFrom:
collectCoverageFrom: [
'<rootDir>/src/**/*.ts',
'!<rootDir>/src/**/*.interface.ts',
'!<rootDir>/src/**/*.mock.ts',
'!<rootDir>/src/**/*.module.ts',
'!<rootDir>/src/**/*.spec.ts',
'!<rootDir>/src/**/*.test.ts',
'!<rootDir>/src/**/*.d.ts'
],
This way I exclude a number of files I do not want to count coverage from, such as my modules, mocks, and tests.
My full file with the original Jest init process and the comments from that.
For a detailed explanation regarding each configuration property, visit: the Jest documentation
module.exports = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after the first failure
// bail: false,
// Respect "browser" field in package.json when resolving modules
// browser: false,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "C:\\Users\\sscott\\AppData\\Local\\Temp\\jest",
// Automatically clear mock calls and instances between every test
// clearMocks: false,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
collectCoverageFrom: [
'<rootDir>/src/**/*.ts',
'!<rootDir>/src/**/*.mock.ts',
'!<rootDir>/src/**/*.module.ts',
'!<rootDir>/src/**/*.spec.ts',
'!<rootDir>/src/**/*.test.ts',
'!<rootDir>/src/**/*.d.ts'
],
// The directory where Jest should output its coverage files
coverageDirectory: "<rootDir>/docs",
// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: [
"\\\\node_modules\\\\"
],
// A list of reporter names that Jest uses when writing coverage reports
coverageReporters: [
"lcov",
"clover",
"text-summary"
],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: null,
// Make calling deprecated APIs throw helpful error messages
errorOnDeprecated: true,
// Force coverage collection from ignored files usin a array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: null,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: null,
// A set of global variables that need to be available in all test environments
globals: {
"ts-jest": {
"diagnostics": false,
"tsConfig": "tsconfig.json"
}
},
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
moduleFileExtensions: [
"ts",
"tsx",
"js"
],
// A map from regular expressions to module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "always",
// A preset that is used as a base for Jest's configuration
// preset: null,
// Run tests from one or more projects
// projects: null,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state between every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: null,
// Automatically restore mock state between every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: null,
// A list of paths to directories that Jest should use to search for files in
roots: [
"<rootDir>/src"
],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// The path to a module that runs some code to configure or set up the testing framework before each test
// setupTestFrameworkScriptFile: null,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: "node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
testMatch: [
"**/*.spec.ts"
],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// The regexp pattern Jest uses to detect test files
// testRegex: "",
// This option allows the use of a custom results processor
// testResultsProcessor: null,
// "testResultsProcessor": "jest-jenkins-reporter",
// This option allows use of a custom test runner
// testRunner: "jasmine2",
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
// A map from regular expressions to paths to transformers
transform: {
"^.+\\.(ts|tsx)$": "ts-jest"
},
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
verbose: false
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
After a lot of research at several pages, this worked for me to get the coverage report:
put below line under scripts:
"test:coverage": "set CI=true && react-scripts test --coverage",
And, add below code for jest configuration in package.json file as below:
"jest": {
"collectCoverageFrom": [
"**/*.{js,jsx}",
"!**/node_modules/**",
"!**/coverage/**",
"!**/serviceWorker.js",
"!**/index.js"
],
"coveragePathIgnorePatterns": [
"/node_modules/",
"package.json",
"package-lock.json"
]
}
And, then run
npm run test:coverage
Apparently you have to add your source files to roots to make it work. See this PR comment.
Instead of this:
roots: ["../src/tests/"]
Also include your source files:
roots: ["../src/tests/", "../src/repositories/"]
After that and having the correct collectCoverageFrom, all files with 0% coverage were detected as expected.

Resources