Jest fails when rendering React component with 'No element indexed by' - javascript

I am attempting to get Jest working for my React Native project and have run into a variety of problems, the most confusing of which is the following:
When I run any test that renders a component, it spits out the error No element indexed by 7.
Here is the full stack trace:
FAIL __tests__/App-test.tsx
● Test suite failed to run
No element indexed by 7
at ArraySet_at [as at] (node_modules/source-map-support/node_modules/source-map/lib/array-set.js:109:9)
at BasicSourceMapConsumer.SourceMapConsumer_originalPositionFor [as originalPositionFor] (node_modules/source-map-support/node_modules/source-map/lib/source-map-consumer.js:673:30)
at mapSourcePosition (node_modules/source-map-support/source-map-support.js:244:42)
at wrapCallSite (node_modules/source-map-support/source-map-support.js:397:20)
at Function.prepareStackTrace (node_modules/source-map-support/source-map-support.js:446:39)
at Function.write (node_modules/#jest/console/build/BufferedConsole.js:101:7)
at console._log (node_modules/#jest/console/build/BufferedConsole.js:117:21)
at console.error (node_modules/#jest/console/build/BufferedConsole.js:161:10)
This same error occurs with any component I attempt to render.
Regarding this issue which purports to solve a similar problem, I have tried installing babel (npm install --save-dev babel-jest #babel/core #babel/preset-env) and setting "coverageProvider" in the jest config to "v8". With or without the v8 preset I am still getting the same errors. It's definitely possible that I configured something else wrong. Here are some code snippets which may be of use:
App-test.tsx
/**
* #format
*/
import 'react-native';
import React from 'react';
import App from '../App';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
renderer.create(<App />);
});
package.json
// ...
"jest": {
"preset": "react-native",
"coverageProvider": "babel",
"transformIgnorePatterns": [
"node_modules/(?!(react-native|#react-native|react-native-video|react-native-reanimated|#miblanchard/react-native-slider|react-native-gesture-handler)/)"
],
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
},
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
]
}
babel.config.js
module.exports = {
presets: [
'module:metro-react-native-babel-preset',
['#babel/preset-typescript', {allowDeclareFields: true}],
],
plugins: [
"react-native-reanimated/plugin",
],
};
As an additional note, I have tried adding #babel/preset-env to the list of babel presets, but this only resulted in a different error related to a separate package added to the transformIgnorePatterns list. Adding source-map-support to said list also solves nothing.
Edited to note that these tests fail regardless of whether or not the --coverage argument is applied

In the end, I solved my error by uninstalling node_modules, re-running npm install --save-dev babel-jest #babel/core #babel/preset-env and adding
"setupFiles": [
"./node_modules/react-native-gesture-handler/jestSetup.js",
// ...
]
to my package.json

Related

Test suite failed to run. Cannot find module '#testing-library/jest-native' running a test using react native testing library

I am running a test for a component that needs to check if it has a particular CSS style. As the React Native Testing Library doesn't have this function by default, I installed the #testing-library/react-native to use toHaveStyle from there but while running a test I get an error: Test suite failed to run. Cannot find module '#testing-library/jest-native' from "a path to my test file here". Here is my test and the jest config:
// test file
import React from 'react';
import {toHaveStyle} from '#testing-library/jest-native';
describe('JobForm', () => {
expect.extend({toHaveStyle});
// ....
});
// package.json
{
//...
"jest": {
"preset": "react-native",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
"transformIgnorePatterns": [
"node_modules/(?!(jest-)?#?react-native|#react-native-community|#react-navigation|aws-amplify-react-native|#ui-kitten)"
],
"setupFiles": [
"<rootDir>/jest.setup.js",
"./node_modules/react-native-gesture-handler/jestSetup.js"
]
}
}
//jest.setup.js
import mockRNCNetInfo from '#react-native-community/netinfo/jest/netinfo-mock.js';
import mockAsyncStorage from '#react-native-async-storage/async-storage/jest/async-storage-mock';
jest.mock('#react-native-community/netinfo', () => mockRNCNetInfo);
jest.mock('#react-native-async-storage/async-storage', () => mockAsyncStorage);
It seems that you forgot to finish the configuration from the Usage section (a section below the Installation section) from the #testing-library/jest-native package. All you need to do is add this line to your setup file:
import '#testing-library/jest-native/extend-expect';
In case of config or import issues it's always a good idea to compare you config against model one provided by RNTL team. RNTL has a basic example app that is useful for that purpose, especially that it also includes #testing-library/jest-native.

Jest / Puppeteer complains that 'export' isn't valid syntax [duplicate]

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"
}

Jest or Mocha with Vue: SyntaxError: Cannot use import statement outside a module

Edit: This post got out of hand with edits, please follow this link to a new Stackoverflow post which is clearer:
SyntaxError: Cannot use import statement outside a module when following vue-test-utils official tutorial
There are thousands of posts and threads about this issue and I still can't fix my problem.
I followed the "Getting started" portions of Jest AND Mocha and get the same error both times:
SyntaxError: Cannot use import statement outside a module but their provided link doesn't help at all.
Theres a new edit at the bottom with steps for a clean new project with jest for you to follow along which results in an error.
"vue-jest": "^3.0.7",
"vue": "^2.6.12",
"#vue/test-utils": "^1.2.2"
package.json
"mocha": "mocha 'tests/Frontend/**/*.test.js'"
example.test.js:
import { mount } from "#vue/test-utils"
import Dashboard from "../../resources/js/views/Dashboard";
import * as assert from "assert";
describe('test example', () => {
it('should work', () => {
assert.equal([1, 2, 3].indexOf(4), -1); // doesn't matter what I do here
})
})
What I've tried:
Using the --require #babel/register flag with mocha
Setting "transformIgnorePatterns": [] and thus allowing all node_modules to be considered
Adding a .babelrc file with the following content: This resulted in following error on building the app though:
Error: Multiple configuration files found. Please remove one:
- package.json
- C:\Users\f.marchi\workspace\projects\sanctum-test\.babelrc
{
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
Can someone confirm, that those docs are missing some very important steps? I really don't know what I'm doing wrong, I'm just following the tutorials.
Edit: jest.config.js:
module.exports = {
clearMocks: true,
collectCoverage: true,
coverageDirectory: "coverage",
moduleFileExtensions: [
"js",
"json",
"vue"
],
transform: {
".*\\.(vue)$": "vue-jest"
},
transformIgnorePatterns: []
};
Edit:
I just tried again, you can follow along if you want:
vue create jest-test
npm install --save-dev jest #vue/test-utils vue-jest
Added jest config to package.json:
{
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
".*\\.(vue)$": "vue-jest"
}
}
}
npm install --save-dev babel-jest #babel/core #babel/preset-env babel-core#^7.0.0-bridge.0
Adjusted jest config to:
{
"jest": {
"transform": {
// process `*.js` files with `babel-jest`
".*\\.(js)$": "babel-jest" //<-- changed this
}
}
}
Adjusted babel config to:
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset',
'#babel/preset-env' //<-- added this
]
};
You should use vue-cli API.
In your package.json add to scripts this:
"test:unit": "vue-cli-service test:unit"
You have vue-cli and test-utils installed so it should now work.

SyntaxError: Cannot use import statement outside a module when following vue-test-utils official tutorial

I can't get vue testing to work with vue-test-utils and jest. I created a clean new project with vue cli and added jest as follows, maybe someone can follow along and tell me what I'm doing wrong. (I'm following this installation guide: https://vue-test-utils.vuejs.org/installation/#semantic-versioning)
vue create jest-test
1.1. npm install
npm install --save-dev jest #vue/test-utils vue-jest
Added jest config to package.json:
{
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
".*\\.(vue)$": "vue-jest"
}
}
}
npm install --save-dev babel-jest #babel/core #babel/preset-env babel-core#^7.0.0-bridge.0
Adjusted jest config to:
{
"jest": {
"transform": {
// process `*.js` files with `babel-jest`
".*\\.(js)$": "babel-jest" //<-- changed this
}
}
}
Adjusted babel config to:
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset',
'#babel/preset-env' //<-- added this
]
};
Created example.test.js in a tests directory under the project root (jest-test/tests)
Added the following to this file:
import { mount } from '#vue/test-utils'
import HelloWorld from "#/components/HelloWorld";
test('displays message', () => {
const wrapper = mount(HelloWorld)
expect(wrapper.text()).toContain('Welcome to Your Vue.js App')
})
Added the following to the package.json scripts:
"jest": "jest"
npm run jest
Get the following error:
C:\Users\xxx\jest-test\tests\example.test.js:1
import { mount } from '#vue/test-utils'
^^^^^^
SyntaxError: Cannot use import statement outside a module
Same happens with Mocha or if I try it in an existing project. Is this a bug? I can't get it working, no matter what I do.
Edit: If I do it with Vue CLI, it works
https://vue-test-utils.vuejs.org/installation/#installation-with-vue-cli-recommended
You need to transform both *.vue files and *.js files.
I tried your setup and could reproduce the issue. But after altering jest.config.js to the following, the tests will run fine:
module.exports = {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
transform: {
'.*\\.js$':'babel-jest',
".*\\.(vue)$": "vue-jest"
},
moduleNameMapper: {
"#/(.*)": "<rootDir>/src/$1",
},
testEnvironment: 'jsdom'
}

Unable to load a react module as node module

I have a react component in the path
src/components/test
import React from 'react';
import ReactDom from 'react-dom';
class TestComp extends React.Component {}
export default TestComp;
I am exposing the component in index.js from path
src/index.js
import TestComp from './components/test';
export {
TestComp
};
I have added main in package.json as "main": "src/index.js"
I have published a npm package test-comp of above application and using same in another application.
main.js
import {TestComp} from 'test-comp';
I am using grunt-browserify in this application with following options set.
options: {
"transform": [
[
"babelify",
{
"presets": [
"es2015",
"react",
"stage-0"
]
}
]
],
browserifyOptions: {
debug: true,
extensions: ['.js', '.jsx'],
entries: ['main.js']
}
}
When I run grunt browserify getting following error.
>> import TestComp from './components/test';
>> ^
>> ParseError: 'import' and 'export' may appear only with 'sourceType: module'
Warning: Error running grunt-browserify. Use --force to continue.
It probably not understanding the path mentioned in node module or rejecting to understand the same which linting. I even have tried adding following in .eslintrc but no luck
{
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"env": {
"browser": true,
"es6": true
},
"ecmaFeatures": {
"modules": true
}
}
I tried most of SO answers related to this error. But still stuck in same place.
EDIT
I am able to browserify first module directly with almost similar configuration. Getting this error when first module is loaded as node dependancy in other application as explained above.
So you wrote the module test-comp in ES6, using import and export, and the main entry of the package.json in test-comp refers to src/index.js.
The answer is that browserify transforms don't apply to every module you require. They only apply to the immediate project: not the project's dependencies.
If you want to require a module that uses ES6 syntax in browserify, you'll either need to
Add a prepublish script to test-comp that transpiles it to ES5, and change the main entry of test-comp to refer to that ES5 version, not the ES6 version
Add babelify as a dependency of test-comp and add babelify as a browserify transform in the package's 'browserify' entry, as documented in babelify.

Categories