Unable to run JEST test - javascript

I'm facing an issue when I try to import something using require() function in jest test file.
script2.test.js
const fetch = require('node-fetch');
it('test function', () => {
expect(4).toEqual(4);
});
Package.json
{
"name": "jest-test",
"version": "1.0.0",
"description": "",
"type": "module",
"scripts": {
"test": "jest --watchAll"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.15.7",
"#babel/core": "^7.15.8",
"#babel/plugin-transform-async-to-generator": "^7.14.5",
"#babel/preset-env": "^7.15.8",
"jest": "^27.3.1"
},
"dependencies": {
"node-fetch": "^3.0.0"
},
"jest": {
"transform": {
"^.+\\.(js|jsx)$": "babel-jest"
}
}
}
babel.config.cjs
module.exports = {presets: ['#babel/preset-env']}
I'm getting following errors when I run the test using npm test
FAIL ./script2.test.js
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
Details:
C:\work\jest-udemy\node_modules\node-fetch\src\index.js:9
import http from 'http';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | const fetch = require('node-fetch');
| ^
I'm new to JEST, any help is much appreciated.
My Node version is 14.17.3
Thanks you.

It seems that one still needs to jump through the hoops to make jest work with ESM.
In package.json change your script to:
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watchAll"
And in script2.test.js use import:
import fetch from 'node-fetch';
P.S. This was tested with node 14.15.1

Related

HOW TO FIx code : 'ERR_REQUIRE_ESM' const { nanoid } = require("nanoid");

how to fix it ,
I'm doing App chat .
Sorry if the language is difficult to read, I'm Thai.
PS C:\Users\ADMIN\Desktop\chat\server> node server.js
C:\Users\ADMIN\Desktop\chat\server\server.js:4
const { nanoid } = require("nanoid");
^
[ERR_REQUIRE_ESM]: require() of ES Module
C:\Users\ADMIN\Desktop\chat\server\node_modules\nanoid\index.js from
at Object.<anonymous> (C:\Users\ADMIN\Desktop\chat\server\server.js:4:20) {
code: 'ERR_REQUIRE_ESM'
{
"name": "chat",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.1",
"nanoid": "^4.0.0",
"socket.io": "^4.5.1"
}
}
The problem is that you are using nanoid Ver.4.0.0 .
It seems that a new feature in V.4 (support for ESM) is a braking change.
The full documentation is in this link to issue#365 in the nanoid GitHub repo.
The comment that helped me and I base my solution on was from #salyndev0
To fix the problem follow these steps:
Uninstall nanoid: npm uninstall nanoid
Install Version 3 supporting all 3.x.x: npm install nanoid#^3.0.0
This means the library you're trying to require cannot be imported using the require syntax.
I think the version of the nanoid you're using needs to be imported using import
You could try downgrading nanoid or switching to the import keyword.

Mocha and Import Syntax: Cannot find module

Maintainer of multiple npm packages here. Been using mocha with the require syntax and wanting to migrate to the import syntax.
The error I am getting is
Cannot find module '<project>/src/index' imported from <project>/test/index.spec.js
Steps to Reproduce
With the following three files
src/index.js
export const sum = (a, b) => a + b;
test/index.spec.js
import { sum } from '../src/index';
const expect = require('chai').expect;
describe('Testing Index', () => {
it('Testing sum', () => {
expect(sum(7, 13)).to.equal(20);
});
});
package.json
{
"name": "mocha-debug",
"type": "module",
"main": "index.js",
"scripts": {
"test": "mocha \"./test/**/*.spec.js\""
},
"license": "ISC",
"devDependencies": {
"chai": "4.3.4",
"mocha": "9.1.4"
}
}
and using node v14.18.2, run yarn install and
yarn test
> `Cannot find module '<project>/src/index' imported from <project>/test/index.spec.js`
Notes
I've found a related issue that recommends using babel with --require #babel/register, but wasn't able to get over the error.
I've set up a test repo to make it easy to reproduce the issue
https://github.com/simlu/mocha-debug
Question
What am I doing wrong here? How do I get the tests to run successfully?
I solved it by just adding the file extension in my case I was importing my mongodb model so I imported with the file extension .ts
var Employee = require('../models/Employee.ts')
Which solved the issue

Jest and Create-react-app: Cannot use import statement outside a module

I have a React Native application where I have some files with some methods that calls certain endpoints. When I try to run Jest is throwing me an error at a local file that is imported.
I have the next package.json:
{
"name": "appName",
"version": "1.0.0",
"description": "some description",
"main": "index.js",
"scripts": {
"test": "jest"
},
"author": "",
"license": "ISC",
"dependencies": {},
"devDependencies": {
"#babel/core": "^7.14.2",
"#react-native-community/async-storage": "^1.12.1",
"#react-native-community/netinfo": "^6.0.0",
"isomorphic-fetch": "^3.0.0",
"jest": "^26.6.3",
"jest-fetch-mock": "^3.0.3"
},
"jest": {
"automock": false,
"setupFiles": [
"./jest.setup.js"
]
}
}
And the jest.setup.js file is the following:
import mockRNCNetInfo from '#react-native-community/netinfo/jest/netinfo-mock.js'
jest.mock('#react-native-community/netinfo', () => mockRNCNetInfo)
For the moment, this content is commented, otherwise will throw the same error like in the picture.
I tried to test the same stuff in another project where this #react-native-community/netinfo package wasn't saved in devDependencies but in dependencies and it worked but I am not sure if this is the problem. In this specific project I can't let this package as a dependency, it should be in devDependencies.
I found a lot of issues on this but none of them worked on this case, I don't know what to do anymore. Thank you for your time!
I got this error when I was creating tests with Create-react-app Typescript Jest Axios. Perhaps the following entry in package.json might help.
"jest": {
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
},
{ "transformIgnorePatterns": [
"node_modules/(?!#shotgunjed)/"
]
},
I found this answer on internet and it worked for me with some small add-ons but I will post it here maybe will help someone in future:
install babel-jest, babel-preset-env, #babel/runtime and react (the last one might be possible to be necessary only if some other package requires it)
create .babelrc file in root directory and add:
{
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
Run your code and should be good to go

'ReferenceError: jest is not defined' when running unit test

I'm in the early stages of a new app that so far just uses vanilla JS. I'm trying to use ES6 modules for my Jest unit tests, so I followed the 2020 updated instructions on making this possible.
However, after following those instructions, I get the error ReferenceError: jest is not defined when running my unit test.
Here's my package.json:
{
"version": "1.0.0",
"main": "app.js",
"type": "module",
"jest": {
"testEnvironment": "jest-environment-node",
"transform": {}
},
"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
"start": "node server.js"
},
"license": "ISC",
"devDependencies": {
"express": "^4.17.1",
"jest": "^26.6.3",
"jest-environment-node": "^26.6.2",
"open": "^7.3.0"
},
"dependencies": {}
}
Below is my test file. The error occurs due to the jest.fn call:
import { getTotalNumPeople } from "./app.js";
test("Get total number of people", async () => {
global.fetch = jest.fn(() => Promise.resolve({
json: () => Promise.resolve({count: 15})
})
)
expect(await getTotalNumPeople()).toBe(15);
});
Any ideas on why this is happening? I'm confident that the issue has to do with the steps I followed to support ES6 modules. Prior to these changes, my test ran fine when I simply pasted the getTotalNumPeople function in my test file.
If I comment out mocking my function, I then get a ReferenceError about fetch not being defined (since getTotalNumPeople uses fetch). So it's not just jest that's not defined.
I notice that if I do not specify jest-environment-node as my test environment, the error changes to ReferenceError: global is not defined due to referring to global.fetch in my test. Just thought I'd note that in case that helps.
It looks like you didn’t import jest, so you have to just add this line to the top of the file:
import {jest} from '#jest/globals'
For more details, see this issue on native support for ES6 modules in Jest.
while essentially the same as the answer of Rupesh - you can expose jest globally without having to import it in each test file - by adding a setup-file to the jest configuration:
"jest": {
"setupFiles": [
"<rootDir>/test-setup.js"
]
}
then add this to test-setup.js:
import { jest } from '#jest/globals';
global.jest = jest;
also in general ESM support for jest is improved by a test script in package.json as so:
"scripts": {
"test": "node --no-warnings --experimental-vm-modules $( [ -f ./node_modules/.bin/jest ] && echo ./node_modules/.bin/jest || which jest )"
},

Problem while Testing ES6 Class with Jest

I'm having a problem making a unitary test with jest over an es6 class. I don't know if the configurations were made properly or if I need some extra package.
This is my file queue.js
export default class Queue {
constructor() {
...
}
//Adds a new elemnt to the queue
method1(element) {
...
}
.
.
.
}
This is my test file
import Queue from "../src/queue";
const myQueue = new Queue();
describe("Queue", () => {
...
...
...
});
This is my .babelrc file
{
"presets": ["es2015"]
}
This is my package.json file. The clean, build and production scripts run all ok, but when I try to run the test, then an error is thrown.
{
"name": "queue",
"version": "1.0.0",
"description": "An implementation of a queue data structure",
"main": "queue.js",
"scripts": {
"test": "jest",
"clean": "rm -dr dist",
"build": "npm run clean && mkdir dist && babel src -s -d dist",
"production": "npm run build && node bin/production"
},
"author": "Osiris Román",
"license": "ISC",
"jest": {
"transform": {
"^.+\\.js$": "babel-jest"
}
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-jest": "^25.4.0",
"babel-preset-es2015": "^6.24.1",
"babel-register": "^6.26.0",
"jest": "^25.3.0"
}
}
This is the error:
Plugin/Preset files are not allowed to export objects, only functions. In /home/usuario/practicing/javascript/queue/node_modules/babel-preset-es2015/lib/index.js
Does someone know how can I solve this problem?
The error you are getting means that one of your presets isn't compatible with the babel version.
Looking at your package.json you are using babel version 6. But both jest and babel-jest use later versions of babel. This causes your es2015 preset not to work correctly.
If you are tied to your current version of babel you can downgrade your jest and babel-jest dependencies to a version that uses older versions of babel:
npm uninstall --save-dev babel-jest jest
npm install --save-dev babel-jest#23.6.0 jest#23.6.0
If not, I would recommend to upgrade your babel version (babel-cli, babel-register and babel-preset-es2015 packages) to newer versions.
If you follow this second path, note that babel-preset-es2015 is deprecated and the use of #babel/preset-env is recommended instead.
I finally found how to solve the problem. I'll share here the configuration If someone else is having the same problem.
This is my file queue.js
export default class Queue {
constructor() {
...
}
//Adds a new elemnt to the queue
method1(element) {
...
}
.
.
.
}
This is my test file
import Queue from "../src/queue";
const myQueue = new Queue();
describe("Queue", () => {
...
...
...
});
I decided to use babel.config.js file insted of .babelrc file. This is the content of this new file.
module.exports = {
presets: [["#babel/preset-env", { targets: { node: "current" } }]],
};
This is my package.json file. The clean, build, dev, production and test scripts run all ok without errors.
{
"name": "queue",
"version": "1.0.0",
"description": "An implementation of a queue data structure",
"main": "queue.js",
"scripts": {
"test": "jest",
"clean": "rm -dr dist",
"build": "npm run clean && babel src -s -d dist ",
"production": "npm run build && node bin/production",
"dev": "npm run build && node bin/dev"
},
"author": "Osiris Román",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.8.4",
"#babel/core": "^7.9.0",
"#babel/preset-env": "^7.9.5",
"#babel/register": "^7.9.0",
"babel-jest": "^25.5.0",
"jest": "^25.3.0"
}
}
Thanks to #mgarcia comment I decided to avoid babel-preset-es2015 to use the recommended #babel/preset-env .

Categories