I am running into problems when trying to test a component with react-native-elements.
I am getting "Cannot use import statement outside a module" on import from react-native-elements.
My babel config is:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: ['#babel/plugin-proposal-numeric-separator'],
};
jest config:
"jest": {
"preset": "react-native",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
"setupFiles": [
"<rootDir>/__tests__/testSetup.ts"
]
}
The test is:
import { Questionnaire } from './Questionnaire';
import { render } from '#testing-library/react-native';
describe('Questionnaire', () => {
it('Should render', () => {
const { container } = render(<Questionnaire setSessionState={jest.fn()} />);
expect(container).toMatchSnapshot();
});
});
Any help would be appreciated!
Related
I am facing an issue with setting up tests for react app with Jest.
I am using workerize-loader! library to import modules into webworkers.
On tests that use the import worker from workerize-loader!./path/to/file are barking on import of the test. I tried with a custom loader, in the jest.condig.js file but that did not work. When I run the default testing script provided by the react app setup it cannot find the imports in the files. But the code when it runs works alright.
I need help with importing the modules inside of the test suite of jest
Basic test
import React from "react";
import {cleanup, fireEvent, render } from "#testing-library/react";
import App from "./App";);
afterEach(cleanup);
test("basic test", () => {
const { container } = render(<App />);
const linkElement = container.firstChild;
expect(linkElement).toBeInTheDocument();
});
Configuration
jest.config.js
module.exports = {
preset: 'ts-jest',
verbose: true,
testEnvironmentOptions: {
url: 'http://localhost/'
},
testEnvironment: 'jsdom',
transform: {
'workerize-loader(\\?.*)?!(.*)': '<rootDir>/workerize-jest.js',
'^.+\\.(js|jsx)$': 'babel-jest',
'^.+\\.(ts|tsx)?$': 'ts-jest',
},
unmockedModulePathPatterns: [
'node_modules',
],
moduleNameMapper: {
'workerize-loader(\\?.*)?!(.*)': 'identity-obj-proxy'
},
};
.babelrc
{
"plugins": [
"syntax-dynamic-import",
"#babel/transform-runtime"
],
"presets": [
[
"es2015",
{
"modules": true
}
],
"react",
"stage-0"
],
"env": {
"start": {
"presets": [
"react-hmre"
]
},
"test": {
"presets": [
[
"es2015",
{
"modules": true
}
],
"react",
"stage-0"
]
}
}
}
Error message on react-scripts test
Cannot find module 'workerize-loader!./workers/css.worker'
In file
> 2 | import worker from 'workerize-loader!./workers/css.worker';
workerize-jest.js
module.exports = {
process(src, filename) {
return `
async function asyncify() { return this.apply(null, arguments); }
module.exports = function() {
const w = require(${JSON.stringify(filename.replace(/^.+!/, ''))});
const m = {};
for (let i in w) m[i] = asyncify.bind(w[i]);
return m;
};
`;
}
};
I'm trying to run a simple test with JavaScript as below.
import React from 'react';
import Customization from 'components/onboarding/customization';
import '#testing-library/jest-dom';
import { render, screen, fireEvent } from '#testing-library/react';
describe('customization render', () => {
it('should render the Hero page with no issue', () => {
render(<Customization />);
const heading = screen.getByText(
/All the Moodmap at one place!/i
);
expect(heading).toBeInTheDocument();
});
it("should call onCLick method on click", () => {
const mockOnClick = jest.fn()
const {container} = render(<Customization />);
const button = getByTestId(container, 'alreadyDownloaded');
fireEvent.click(button);
expect(mockOnClick).toHaveBeenCalledTimes(1)
// const mockOnClick = jest.fn()
// const utils = render(<Customization onClick={mockOnClick} />)
// fireEvent.click(screen.getByText(/already downloaded ⟶/i))
// expect(mockOnClick).toHaveBeenCalledTimes(1)
})
});
When running the tests I'm getting this error
No google analytics trackingId defined
8 | debug: process.env.NODE_ENV !== 'production',
9 | plugins: [
> 10 | googleAnalyticsPlugin({
| ^
11 | trackingId: process.env.NEXT_PUBLIC_GA_TRACKING_ID,
12 | }),
How do I make this error go away - surely it shouldn't require Google Analytics code given the above, it's not in production when running the test?
Update
So I need to make sure the .env file is being loaded!
In my package.json I've got this Jest setup:
"jest": {
"testMatch": [
"**/?(*.)(spec|test).?(m)js?(x)"
],
"moduleNameMapper": {
"\\.(css|less|scss)$": "identity-obj-proxy"
},
"moduleDirectories": [
"node_modules",
"src"
],
"rootDir": "src",
"moduleFileExtensions": [
"js",
"jsx",
"mjs"
],
"transform": {
"^.+\\.m?jsx?$": "babel-jest"
},
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": -10
}
}
},
updated code to use jest.setup - can't get env to load
So
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import "#testing-library/jest-dom";
configure({
adapter: new Adapter()
});
module.exports = {
testMatch: [
"**/?(*.)(spec|test).?(m)js?(x)"
],
moduleNameMapper: {
"\\.(css|less|scss)$": "identity-obj-proxy"
},
moduleDirectories: [
"node_modules",
"src"
],
rootDir: "src",
moduleFileExtensions: [
"js",
"jsx",
"mjs"
],
transform: {
"^.+\\.m?jsx?$": "babel-jest"
},
coverageThreshold: {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": -10
}
},
setupFiles: ["../<rootDir>/.config.env.test"]
};
The environment variable files is here:
process.env.NEXT_PUBLIC_GA_TRACKING_ID=xxx
And this is the code that is not loading the environment variables properly.
import Analytics from 'analytics';
import googleAnalyticsPlugin from '#analytics/google-analytics';
import Router from 'next/router';
// Initialize analytics and plugins
// Documentation: https://getanalytics.io
const analytics = Analytics({
debug: process.env.NODE_ENV !== 'production',
plugins: [
googleAnalyticsPlugin({
trackingId: process.env.NEXT_PUBLIC_GA_TRACKING_ID,
}),
],
});
During your tests you can leverage loadEnvConfig from #next/env to make sure your environment variables are loaded the same way Next.js does.
First setup a .env.test to be used during the tests.
NEXT_PUBLIC_GA_TRACKING_ID=ga-test-id
Next, create a Jest global setup file if you don't have one yet, and reference it in your jest.config.js.
// jest.config.js
module.exports = {
//...
setupFilesAfterEnv: ['./jest.setup.js'],
};
Then add the following code into your Jest global setup file.
// jest.setup.js
import { loadEnvConfig } from '#next/env'
loadEnvConfig(process.cwd())
This message means that the trackingId is not defined. As you can see it read from the process.env. You need to create this file in the root of your project and call it .env. Note that the dot is at the beginning of the filename. The content of the file should be as follow:
NEXT_PUBLIC_GA_TRACKING_ID=insert-key-here
If your env file is not being read by jest you can do the following:
// In jest.config.js :
module.exports = {
....
setupFiles: ["<rootDir>/test/setup-tests.ts"]
}
// The file test/test-setup.ts:
import dotenv from 'dotenv';
dotenv.config({path: './config.env.test'});
You can also check this article for more details.
I am using react + typescript + jest done the intial setup's but when i try to the run the test i am getting the following error:
const component = enzyme_1.shallow(<Dummy_1.default />).contains(<h1>Hello</h1>);
^
SyntaxError: Unexpected token <
Package.json
"jest": {
"setupFiles": [
"<rootDir>/tests/setup/test-shim.js",
"<rootDir>/tests/setup/test-setup.js"
],
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"transform": {
"^.+\\.(ts|tsx)$": "ts-jest"
},
"testMatch": [
"**/tests/*.(ts|tsx|js)"
]
},
Test file:
import React from 'react';
import { shallow } from 'enzyme';
import Dummy from '../src/Dummy';
it('renders dummy page', () => {
const component = shallow(<Dummy />).contains(<h1>Hello</h1>);
expect(component).toBeTruthy();
});
I have tried adding preset in jest but i got the same error only. I have not installed babelrc do i need to install it? I have created the app using create-react-app
I'm trying to test a component using the react-test-renderer library and i'm getting this error.
Header.test.js:
import ReactShallowRenderer from "react-test-renderer/shallow";
import React from "react";
import Header from "../../components/Header/Header";
test("should render Header correctly", () => {
const renderer = new ReactShallowRenderer();
renderer.render(<Header />);
// Returning the render output of the jsx
console.log(renderer.getRenderOutput());
});
That's my jest config:
"jest": {
"verbose": true,
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.(css|scss|less)$": "jest-css-modules"
}
My babelrc:
{
"env": {
"development": {
"plugins": ["transform-es2015-modules-commonjs"]
},
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
I've created a new repo that replicates this problem found here: https://github.com/davidRoussov/jest-webpack-alias
It's a React app bootstrapped using create-react-app, but it has been ejected. The error I'm getting when I run npm run test is this:
FAIL src\components\Parent.test.js
● Test suite failed to run
Invariant Violation: Target container is not a DOM element.
at invariant (node_modules/fbjs/lib/invariant.js:42:15)
at Object.<anonymous> (src/index.js:7:20)
at Object.<anonymous> (src/components/Parent.js:2:14)
at Object.<anonymous> (src/components/Parent.test.js:2:15)
at process._tickCallback (internal/process/next_tick.js:103:7)
The component being tested, Parent.js:
import React, { Component } from 'react';
import Child from '#/components/Child';
class Parent extends Component {
render() {
return (
<div>
<Child/>
</div>
);
}
}
export default Parent;
The test, Parent.test.js:
import React from 'react';
import Parent from './Parent';
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Parent/>
).toJSON();
expect(tree).toMatchSnapshot();
});
For the webpack config I've only added:
function resolve(dir) {
return path.join(__dirname, '..', dir)
}
And:
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
'#': resolve('src')
},
The Jest config:
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.js?(x)",
"<rootDir>/src/**/?(*.)(spec|test).js?(x)"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"
],
"moduleDirectories": ["node_modules"],
"modulePaths": ["src"],
"moduleNameMapper": {
"^#(.*)$": "<rootDir>/src",
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx",
"node"
]
},
Jest does not produce errors if import Child from '#/components/Child'; is replaced with import Child from './Child';
I hope it's not too late, you forgot to substitute the captured regex groups in the path , like so:
"moduleNameMapper": {
"^#(.*)$": "<rootDir>/src/$1",
},
Link to the documentation