I have a React app that has Jest tests. I'm configuring Jest in my package.json:
…
"jest": {
"setupEnvScriptFile": "./test/jestenv.js",
"setupTestFrameworkScriptFile": "./test/setup-jasmine-env.js",
"testRunner": "node_modules/jest-cli/src/testRunners/jasmine/jasmine2.js",
"unmockedModulePathPatterns": [
"./node_modules/q",
"./node_modules/react"
]
},
…
The setup-jasmine-env.js looks like this:
var jasmineReporters = require('jasmine-reporters');
jasmine.VERBOSE = true;
jasmine.getEnv().addReporter(
new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: "output/",
filePrefix: "test-results"
})
);
It took a bit of working to get that jasmine env setup correctly, but I"m not seeing anything in the output directory (indeed, it isn't created and creating it myself doesn't help). I suspect that my alterations to the jasmine var aren't the same one that Jest is using, but I can't figure out how to hook them together.
If you use a more recent version of jest (I'm looking at 16.0.2), you don't need to specify the testrunner because jasmine is the default. You also don't need the unmockedModulePathPatterns section of the jest config.
I.e. you just need to include the following devDependencies in your package.json:
"jasmine-reporters": "^2.2.0",
"jest": "^16.0.2",
"jest-cli": "^16.0.2"
And add this jest config to your package.json (note: you no longer need the unmockedModulePathPatterns section):
"jest": {
"setupTestFrameworkScriptFile": "./setup-jasmine-env.js"
}
And then use Drew's setup-jasmine-env.js from the question.
Jest has support for its own reporters via the testResultsProcessor config. So I wrote up a little thing that generates compatible junit xml for this. You can find it here. https://github.com/palmerj3/jest-junit
looks like all you're missing from the above setup is to add jasmine-reporters to unmockedModulePathPatterns, so give the following a go:
"jest": {
...
"unmockedModulePathPatterns": [
"./node_modules/q",
"./node_modules/react",
"./node_modules/jasmine-reporters"
]
},
Hope that helps!
UPDATE: for anyone else experiencing this problem, I have put a working demo up here.
Related
I used to solve similar errors while I was using Jest with only JavaScript, but currently I'm not able to do so with Typescript.
All my tests were running fine until I installed Puppeteer which requires #types/jest-environment-puppeteer, #types/puppeteer and #types/expect-puppeteer.
After installing them, puppeteer tests are running perfectly, but other tests started to fail with below error.
D:\...\api\node_modules\uuid\dist\esm-browser\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
^^^^^^
SyntaxError: Unexpected token 'export'
at Runtime.createScriptFromCode (../node_modules/jest-runtime/build/index.js:1796:14)
at Object.require (../node_modules/#nestjs/common/decorators/core/injectable.decorator.js:4:16)
WHAT I DID?
allowJs: true on tsconfig.json and set the transformIgnorePatterns on jest configs. So that jest can compile files from node_modules/
After that this error stopped but test failed for another strange reason.
And worse is that test start time have increased too much.
So I left allowJs as in original setup and updated jest config from
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
to
"transform": {
"^.+\\.(t)s$": "ts-jest"
}
So currently ts-jest doesnt compile js files. But I think I am not able to make babel pick the transformation for js files. These are my jest configs:
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t)s$": "ts-jest",
"^.+\\.(js|jsx)$": "babel-jest"
},
"transformIgnorePatterns": ["<rootDir>/node_modules/.+.(js|jsx)$"]
}
Thanks to this reply:
https://stackoverflow.com/a/54117206/15741905
I started googling for similar fixes and ended up here:
https://github.com/uuidjs/uuid/issues/451
And this solved my problem: https://github.com/uuidjs/uuid/issues/451#issuecomment-1112328417
// jest.config.js
{
//................
moduleNameMapper: {
// Force module uuid to resolve with the CJS entry point, because Jest does not support package.json.exports. See https://github.com/uuidjs/uuid/issues/451
"uuid": require.resolve('uuid'),
}
}
Tough I would still be happy if there is solution to this by using jest-babel.
Because I had to carry jest configs from package.json to a seperate .js file.
Edit:
According to this github issue compatibility issue has been solved with the latest release of the uuid library.
Simply adding moduleNameMapper:{"^uuid$": "uuid"} into my jest.config.js fixed the issue for me:
transient dependency uuid: ^8.3.2
jest: 28.1.3
angular: 14.0.1
Upgrade to uuidv4() version 9.0.0 ("uuid": "^9.0.0") now fixes the the issue. See comment from SimenB: https://github.com/uuidjs/uuid/issues/451#issuecomment-1377099565
I tried the answer above initially, adding moduleNameMapper:{"^uuid$": "uuid"} into my jest.config.js, which fixed the issue for me. Then I followed the link (above) to read more and I saw that it has been fixed in "uuid": "^9.0.0".
So I took out the fix, installed latest uuidv4() at version 9.0.0, (package link below) and it started working fine again. No more errors and tests are running fine, again. https://www.npmjs.com/package/uuid
My React App started having the issues after updating "jest": "26.0.1" to "jest": "29.4.1", "environment-jsdom-fifteen": "1.0.2" to "jest-environment-jsdom": "29.4.1". along with other updates "ts-jest": "26.5.6" to "ts-jest": "^29.0.5". However, as mentioned above, upgrading to uuid version 9.0.0 has fixed it.
Date : 2/15/2023
Jest Version : "#types/jest": "^29.4.0",
UUID Version : "uuid": "^9.0.0"
using the jest.config.ts will generate an error that says
Multiple configurations found
here's how you can override that
/**
* #format
*/
import 'react-native';
import React from 'react';
import App from '../src/App';
import {v4 as uuidv4} from 'uuid';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
renderer.create(<App />);
});
jest.mock('uuid', () => {
return {
v4: jest.fn(() => 1)
}
})
Hoping this will solve other peoples error if the correct answer is not working for you :).
adding this to the package.json file solved it for me:
"devDependencies": {
....
},
"browser": {
"uuid": "./node_modules/uuid/dist/esm-browser/index.js"
}
I'm making a simple snapshot test with Jest and just get this error:
home.test.js
import React from 'react';
import Home from './index';
import renderer from 'react-test-renderer';
it('renders home', ()=> {
const view = renderer.create(
<Home></Home>
).toJSON();
expect(view).toMatchSnapshot();
});
Unfortunately I don't have idea what is the problem here. I thought the test is well written.
Any help would be great.
HOW I SOLVED THE ERROR KEEPING MY TEST FROM RUNNING
Ran into this error, which kept my tests from running
Error Page
After many hours of frustration, in which I deleted the node_modules folder twice and reinstalled and scoured through Stackoverflow and Google without any solution, I decided to create a new CRNA project and see if it would have the same issues.
When I saw the issues didn’t exist in the new repo, I used the following steps to get it to work:
Delete the node_modules folder again
Upgraded my package.json file, with the key changes shown below:
```
{
"devDependencies": {
"react-native-scripts": "1.5.0",
"jest-expo": "^21.0.2",
"react-test-renderer": "16.0.0-alpha.12"
},
"jest": {
"preset": "jest-expo",
"transformIgnorePatterns": [
"node_modules/(?!react-native|expo|react-navigation|native-base-shoutem-theme|#shoutem/theme|#shoutem/animation|#shoutem/ui|tcomb-form-native)"
]
},
"dependencies": {
"react-native": “0.48.4”,
"expo": "^21.0.2",
"react": "16.0.0-alpha.12"
},
3. The core difference was in upgrading react-native from 0.48.0 to 0.48.4; react-native-scripts from 1.2.1 to 1.5.0 and including the transformIgnorePatterns under the jest option.
NOTE: The portion from *native-base* in the transformIgnorePatterns was included because I used NativeBase in the project.
4. I then added a .babelrc with the following details:
{
"presets": ["babel-preset-expo"],
"env": {
"development": {
"plugins": ["transform-react-jsx-source"]
}
}
}
```
5. Running the tests now give me the result:
Passing Tests
All tests are green
I don't get moment.js or other external libraries like tinymce working in my amber application.
These are the steps I did so far:
run bower install moment --save
added a moment.and.json in my applications root directory containing the correct path in bower_components:
{"paths": {"moment": "moment"}}
added "moment" to deploy.js
run grunt devel
My first problem is that from inside the js console momentjs seems to be not loaded, even if the file shows up in network traffic.
After that how do I use moment.js from inside Amber?
How do I need to wrap it?
I read how-to-add-a-non-amber-library-with-bower-for-example-processing and all the other explanations but still have problems grabbing the exact process.
All the documentation I read was inconclusive to me. Isn't there a simple explanation on how to do it?
The amd file has to look like this:
{
"paths": {
"moment": "moment"
},
"shim": {
"moment": {
"exports": "moment"
}
},
"config": {
"moment": {
"noGlobal": false
}
}
}
As it seems it has to be required like this to work properly: window.moment = require('moment');
I've been reading articles on this all morning trying to get my environment setup correctly. But for some reason I'm not getting it. My setup-
/app
... source (mixed js and ts)
/scripts
... copied source (js)
typescripts.js // transpiled typescript with inline mapping
Tests run fine, and with the mapping debugging in the chrome debugger is mapped correctly. But Istanbul sees the typescripts.js file as one file instead of the concatenation of dozens of other files.
To generate the typescript source I'm using gulp-typescript. The source (excluding tests) are transpiled to the aforementioned typescripts.js, and the tests are transpiled individually and copied to /scripts.
var ts = require('gulp-typescript');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
module.exports = function (gulp, config) {
'use strict';
// Runs dot ts files found in `www` through the typescript compiler and copies them as js
// files to the scripts directory
gulp.task('typescript', ['typescript:tests'], function () {
return gulp.src(config.paths.typescript) // [ './www/app/**/*.ts', '!./www/app/**/*.test.ts', '!./www/app/**/*.mock.ts' ]
.pipe(sourcemaps.init())
.pipe(ts(ts.createProject(config.paths.tsConfig))) // './tsconfig.json'
.js
.pipe(concat(config.sourcemaps.dest)) // typescripts.js
.pipe(sourcemaps.write(config.sourcemaps)) // { includeContent: false, sourceRoot: '/app' } - i've also tried absolute local path
.pipe(gulp.dest(config.paths.tmpScripts)); // ./www/scripts
});
gulp.task('typescript:tests', [], function() {
return gulp.src(config.paths.typescriptTests) // [ './www/app/**/*.test.ts', './www/app/**/*.mock.ts' ]
.pipe(ts(ts.createProject(config.paths.tsConfig))) // './tsconfig.json'
.pipe(gulp.dest(config.paths.tmpScripts)); // ./www/scripts
});
};
The resulting typescripts.js has the inline sourcemap. With the sourcemap, the dozen or so ts files results in 106kb.
So from here tests and debugging works fine.
Now in an attempt to get Istanbul code coverage working properly i've installed karma-sourcemap-loader and added it to the preprocessors.
preprocessors: {
'www/scripts/typescripts.js': ['sourcemap'],
'www/scripts/**/*.js': ['coverage']
},
I'd think this is what I'd need to do. But it does not show code coverage on the source files. I tried the absolute path from C:/ but that didn't work either. I also tried the different options in gulp-sourcemaps like adding source (which pushed the file to 160kb) but no like either.
Has anyone gotten this to work? Any ideas what I could be doing wrong?
TL;DR: There is a tool: https://github.com/SitePen/remap-istanbul described as A tool for remapping Istanbul coverage via Source Maps
The article on Sitepan describes it in more detail:
Intern as well as other JavaScript testing frameworks utilise Istanbul
for their code coverage analysis. As we started to adopt more and more
TypeScript for our own projects, we continued to struggle with getting
a clear picture of our code coverage as all the reports only included
the coverage of our emitted code. We had to try to use the compilers
in our minds to try to figure out where we were missing test coverage.
We also like to set metrics around our coverage to let us track if we
are headed the right direction.
A couple of us started exploring how we might be able to accomplish
mapping the coverage report back to its origins and after a bit of
work, we created remap-istanbul, a package that allows Istanbul
coverage information to be mapped back to its source when there are
Source Maps available. While we have been focused on TypeScript, it
can be used wherever the coverage is being produced on emitted code,
including the tools mentioned above!
How to use the tool with gulp: https://github.com/SitePen/remap-istanbul#gulp-plugin
If you want source map support with Istanbul, you can use the 1.0 alpha release as the current release does not support source maps. I have it set up using ts-node in http://github.com/typings/typings (see https://github.com/typings/typings/blob/bff1abad91dabec1cd8a744e0dd3f54b613830b5/package.json#L19) and source code is being mapped. It looks great and is nice to have my tests and code coverage all running in-process with zero transpilation. Of course, you can use Istanbul 1.0 with the transpiled JavaScript.
For the browser implementation you're using, I'd have to see more of code of what you're doing to see this'll just work for you, but try the 1.0.0-alpha.2 and see what happens.
As blakeembrey mentioned. Istanbul 1.x handles it well.
Below an example of pure npm script that does it with Jasmine.
See https://github.com/Izhaki/Typescript-Jasmine-Istanbul-Boilerplate.
package.json (the relevant stuff)
{
"scripts": {
"postinstall": "typings install dt~jasmine --save --global",
"test": "ts-node node_modules/.bin/jasmine JASMINE_CONFIG_PATH=jasmine.json",
"test:coverage": "ts-node node_modules/istanbul/lib/cli.js cover -e .ts -x \"*.d.ts\" -x \"*.spec.ts\" node_modules/jasmine/bin/jasmine.js -- JASMINE_CONFIG_PATH=jasmine.json"
},
"devDependencies": {
"istanbul": "^1.1.0-alpha.1",
"jasmine": "^2.4.1",
"ts-node": "^0.9.3",
"typescript": "^1.8.10",
"typings": "^1.3.1"
},
}
Output
This is repo works. I ran the repo and can see the tests running. Html view is also generated.
https://github.com/Izhaki/Typescript-Jasmine-Istanbul-Boilerplate
None of the examples provided worked for my Node.JS project (written in TypeScript). I wanted to run unit tests in Jasmine, and covered by Istanbul.
I ended up getting it working with the following.
package.json:
{
"scripts": {
"lint": "tslint 'src/**/*.ts'",
"remap": "./node_modules/.bin/remap-istanbul -i ./coverage/coverage-final.json -t html -o ./coverage && rimraf ./coverage/dist",
"test": "npm run lint && rimraf dist coverage && tsc --project tsconfig-test.json && ./node_modules/.bin/istanbul cover ./node_modules/.bin/jasmine JASMINE_CONFIG_PATH=jasmine.json && npm run remap"
},
"devDependencies": {
"#types/jasmine": "2.8.6",
"#types/node": "9.6.6",
"istanbul": "0.4.5",
"jasmine": "3.1.0",
"remap-istanbul": "0.11.1",
"rimraf": "2.6.2",
"tslint": "5.9.1",
"typescript": "2.8.1"
}
}
jasmine.json
{
"spec_dir": "dist",
"spec_files": [
"**/*.spec.js"
],
"stopSpecOnExpectationFailure": false,
"random": false
}
.istanbul.yml
instrumentation:
root: ./dist
excludes: ['**/*.spec.js', '**/fixtures/*.js']
include-all-sources: true
reporting:
reports:
- html
- json
- text-summary
dir: ./coverage
tsconfig-test.json
{
"compilerOptions": {
"declaration": true,
"lib": [
"dom",
"es6"
],
"module": "commonjs",
"noImplicitAny": true,
"outDir": "dist",
"sourceMap": true,
"target": "es5"
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
]
}
Happy Thanksgiving All!
I'm running into a situation and I'm hoping someone can help me out. I have a package.json file, and I'm trying to transpile es6 but not exactly sure what I'm doing wrong. I have a JS Fiddle of my current package.json: http://jsfiddle.net/jdubba/nnhytbdr/ but mainly, i have this line here:
{
"name": "react-starter",
"browserify": {
"transform": [
"reactify"
]
},
"scripts": {
...
From what I've been reading, in the "browserify" object, under "transform", i'm supposed to be able to do something like:
{
"presets": ["es2015", "react"]
}
But i'm doing this incorrectly. I'm going off of what I found here: https://github.com/andreypopp/reactify
When I change my transform array to:
"transform": [
["reactify", {"es6": true}]
]
and then add an import statement into my code, I get the following error:
Parse Error: Line 2: Illegal import declaration while parsing file:
Which then inevitably sent me down another path of findings:
https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=Parse+Error+Illegal+import+declaration+while+parsing
but I haven't found anything to fix my issue, and I feel like i'm going in circles. This illegal import declaration error is pretty common, but I'm interested in a solution that works without having to use grunt or gulp (which is mainly what I've been seeing). Can anyone lend a hand?
I ended up making the following change to my package.json:
"browserify": {
"transform": [
"babelify"
]
},
...
I was not able to get babelify v7.2.0 to work with import/export, so switching to v6.1.2 gave me the results I wanted.