Typescript test with Jest with Enzyme does not recognise components - reactjs

I have a test for Typescript using Jest with Enzyme. Tests work perfect but when i add a component, it gives me a Unterminated regular expression error
import {} from 'jasmine';
import {shallow} from 'enzyme';
import {Show, Hide} from '../components/show_hide';
describe('<Show /> Tests', () => {
it('Show should render once', () => {
const component = shallow(<Show />);
expect(component).toHaveLength(1);
})
})
When I run yarn test the result on the console is
FAIL __tests__/show_hide.ts
● Test suite failed to run
/path/to/repo/__tests__/show_hide.ts: Unterminated regular expression (4:35)
2 | describe('<Show /> Tests', () => {
3 | it('Show should render once', () => {
> 4 | const component = shallow(/>);, expect(component).toHaveLength(1));
| ^
5 | });
6 | });
7 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2hvd19oaWRlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vX190ZXN0c19fL3Nob3dfaGlkZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFDQSxPQUFPLEVBQUMsT0FBTyxFQUFDLE1BQU0sUUFBUSxDQUFDO0FBRy9CLFFBQVEsQ0FBQyxnQkFBZ0IsRUFBRTtJQUMxQixFQUFFLENBQUMsbUJBQW1CLEVBQUU7UUFDdkIsTUFBTSxTQUFTLEdBQUcsT0FBTyxDQUFPLElBQUksRUFDcEMsTUFBTSxDQUFDLFNBQVMsQ0FBQyxDQUFDLFlBQVksQ0FBQyxDQUFDLENBQUMsQ0FBQSxDQUFDO0lBQ25DLENBQUMsQ0FBQyxDQUFBO0FBQ0gsQ0FBQyxDQUFDLENBQUEifQ==
The jest configuration inside package.json is
"jest": {
"transform": {
"^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"json"
],
},
Any thoughts on that?

ts files are for pure typescript code, and tsx for react (like jsx).
Rename the file to tsx

It seems that forgetting to import React caused the issue.

Related

Why do i get this error, Cannot use import statement outside a module

so im trying to make a test for my component a simple test that shows if the component was rendered
test('Should render the movie info', () => {
renderWithContext(<MovieInfo movie={mockMovies[0]} />);
expect(screen.getByText('Terrifier 2')).toBeInTheDocument();
});
but i get this error:
SyntaxError: Cannot use import statement outside a module
the problem seems to have be about axios some how because it happens when trying to import axios.
> 2 | import axios from 'axios';
| ^
i have a jest.config.js file like this.
const { compilerOptions } = require('./tsconfig.json');
const { pathsToModuleNameMapper } = require('ts-jest');
const { default: tsjPreset } = require('ts-jest');
module.exports = {
transform: {
...tsjPreset.transform,
'+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2|pdf)$':
'jest-transform-stub',
'^.+\\.ts?$': 'ts-jest',
},
moduleDirectories: ['src', 'node_modules'],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
transformIgnorePatterns: ['node_modules/(?!(axios)/)'],
};
and i have installed ts-jest, #types/jest and jest-transform-stub as dependencies
i have looked on the internet and this seems to be about some jest config that im doing wrong but nothing i do works
I solved this by adding this to my package.json i think its a hacky way of doing it but is the only way it worked for me.
"test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!axios)/\"",

Jest / React Testing Library, So Many Errors

I'm new to React Testing Library and Jest. I could successfully run a simple set of tests on it, like the below,
but when I tried to test on my "App.js", where a lot of imports/requires, it started to get a many set of errors on the each import, and I'm tbh overwhelmed.
Here's a working example:
./src/dev/test/AppTmp.js
import React from "react";
export const Topbar = () => {
return (
<>
<p>hoge.</p>
</>
)
}
./src/__tests__/hello.js
import '#testing-library/jest-dom/extend-expect'
import React from 'react'
import { render, screen } from '#testing-library/react'
import * as renderer from "react-test-renderer";
import { Topbar } from '../dev/test/AppTmp'
test('tmp test.', () => {
const component = renderer.create(
<Topbar />,
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
})
The above successfully runs.
A problem is when I add an import line like this:
./src/dev/test/AppTmp.js
import React from "react";
import ReactMarkdown from 'react-markdown'; // <--- added this
export const Topbar = () => {
return (
<>
<p>hoge.</p>
</>
)
}
./src/__tests__/hello.js
import '#testing-library/jest-dom/extend-expect'
import React from 'react'
import { render, screen } from '#testing-library/react'
import * as renderer from "react-test-renderer";
import { Topbar } from '../dev/test/AppTmp'
test('tmp test.', () => {
const component = renderer.create(
<Topbar />,
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
})
The above, with just an extra import line, causes the following error:
● 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.
By default "node_modules" folder is ignored by transformers.
...
...
Details:
/home/user/pg/react/myapp/node_modules/react-markdown/index.js:6
export {uriTransformer} from './lib/uri-transformer.js'
^^^^^^
SyntaxError: Unexpected token 'export'
24 | import "prismjs/themes/prism-tomorrow.css";
25 | import { LoremIpsum } from "react-lorem-ipsum";
> 26 | import ReactMarkdown from 'react-markdown';
| ^
27 |
28 | export const Topbar = () => {
29 | return (
at Runtime.createScriptFromCode (../node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (dev/test/AppTmp.js:26:1)
Test Suites: 1 failed, 2 passed, 3 total
(note: actually I had more lines as showing above, but what I'm doing is essentially the same, so kindly ignore them)
So this is an SyntaxError: Unexpected token 'export' error. Well, At first I thought I'm going to solve the error on SO or Google. But the error hell continues...
Now I added a different line as the following.
./src/dev/test/AppTmp.js
import React from "react";
// import ReactMarkdown from 'react-markdown';
import Slider from "react-slick"; // <--- added this
export const Topbar = () => {
return (
<>
<p>hoge.</p>
</>
)
}
The above caused an error:
● Test suite failed to run
matchMedia not present, legacy browsers require a polyfill
25 | import { LoremIpsum } from "react-lorem-ipsum";
26 | // import ReactMarkdown from 'react-markdown';
> 27 | import Slider from "react-slick";
| ^
28 | import "slick-carousel/slick/slick.css";
29 | import "slick-carousel/slick/slick-theme.css";
30 | import 'bootstrap';
at new MediaQueryDispatch (../node_modules/enquire.js/src/MediaQueryDispatch.js:15:15)
at Object.<anonymous> (../node_modules/enquire.js/src/index.js:2:18)
at Object.<anonymous> (../node_modules/react-slick/lib/slider.js:50:53)
at Object.<anonymous> (../node_modules/react-slick/lib/index.js:8:38)
at Object.<anonymous> (dev/test/AppTmp.js:27:1)
at Object.<anonymous> (__tests__/hello.js:8:1)
Test Suites: 1 failed, 2 passed, 3 total
This time I got an matchMedia not present, legacy browsers require a polyfill error.
Error hell continues. Next I tried:
./src/dev/test/AppTmp.js
import React from "react";
// import ReactMarkdown from 'react-markdown';
// import Slider from "react-slick";
import { nanoid } from 'nanoid'; // <--- added this
export const Topbar = () => {
return (
<>
<p>hoge.</p>
</>
)
}
● 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.
By default "node_modules" folder is ignored by transformers.
...
...
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/home/user/pg/react/myapp/node_modules/nanoid/index.browser.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { urlAlphabet } from './url-alphabet/index.js'
^^^^^^
SyntaxError: Cannot use import statement outside a module
49 | // import uniqueId from 'lodash/utility/uniqueId'
50 | import _ from 'lodash'
> 51 | import { nanoid } from 'nanoid';
| ^
52 | import { WithContext as ReactTags } from 'react-tag-input';
53 |
54 | const mymodules = require("./../../mymodules.js")
at Runtime.createScriptFromCode (../node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (dev/test/AppTmp.js:51:1)
Test Suites: 1 failed, 2 passed, 3 total
This time, got an error SyntaxError: Cannot use import statement outside a module. What the hell is going on.....
./.babelrc
{
"presets": [
[
"#babel/preset-env",
{
"loose": true,
"modules": false,
"targets": {
"browsers": "last 2 chrome versions"
}
}
],
"#babel/preset-react"
],
"plugins": [
"react-hot-loader/babel",
["#babel/plugin-proposal-class-properties", { "loose": true }]
],
"env": {
"test": {
"presets": [
[
"#babel/preset-env",
{
"loose": true,
"modules": false
}
],
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-transform-runtime",
"#babel/plugin-transform-modules-commonjs"
]
}
}
}
./package.json
"jest": {
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less|scss)$": "<rootDir>/__mocks__/styleMock.js"
},
"transform": {
"\\.[jt]sx?$": "babel-jest"
},
"moduleFileExtensions": [
"js",
"jsx",
"tsx"
],
"moduleDirectories": [
"node_modules"
],
"rootDir": "src",
"transformIgnorePatterns": [
"/node_modules/(?![#autofiy/autofiyable|#autofiy/property]).+\\.js$",
"/node_modules/(?![#autofiy/autofiyable|#autofiy/property]).+\\.ts$",
"/node_modules/(?![#autofiy/autofiyable|#autofiy/property]).+\\.tsx$",
"/node_modules/(?!my-package)(.*)",
"/node_modules/(?!#ngrx|(?!deck.gl)|ng-dynamic)"
],
"testEnvironment": "jsdom"
},
So, what's the best thing I can do now?
actually I've been taking 8 hours so far on Jest to get the above-mentioned simple example working, I didn't expect just a testing development environment building is this damn hard way.
I mean I think I'm doing something fundamentally wrong. that's why I'm getting this many errors no? What's not right with this setup, can I ask a help? Thanks.

Why is jest test not recognizing react native components?

I have a react native app that I am trying to run tests on, I have set up a basic greeting component as shown below called Greetings.js:
import React from 'react';
import {View, Text} from 'react-native';
const Greetings = ({hello}) => {
return (
<View>
<Text>{hello}</Text>
</View>
);
};
export default Greetings;
This is the test I am running called Greetings.test.js:
import React from 'react';
import {render, screen} from '#testing-library/react-native';
import Greetings from './Greetings';
describe('Greetings component', () => {
it('renders hello world as a test', () => {
render(<Greetings hello="Hello World!" />);
const helloWorldElement = screen.getByText('Hello World!');
expect(helloWorldElement).toBeInTheDocument();
});
});
For some reason it doesnt recognise the react native components, this is the error when running the test:
FAIL app/__tests__/components/Account/Greetings.test.js
● Console
console.error
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You li
forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `Greetings`.
at Greetings (C:\Users\meeve\OneDrive\Desktop\Cozify\smartliving-app\app\__tests__\components\Account\Greetings.js:4:21)
5 | return (
6 | <View>
> 7 | <Text>{hello}</Text>
| ^
8 | </View>
9 | );
10 | };
at printWarning (node_modules/react/cjs/react.development.js:220:30)
at error (node_modules/react/cjs/react.development.js:196:5)
at Object.createElementWithValidation [as createElement] (node_modules/react/cjs/react.development.js:2215:7)
at Greetings (app/__tests__/components/Account/Greetings.js:7:7)
at renderWithHooks (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6016:18)
at mountIndeterminateComponent (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8744:13)
at beginWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:9966:16)
at performUnitOfWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:13800:12)
It shows the same error for the View Component.
Should it not automatically recognize these components after initial setup?
I have installed the following:
yarn add install -dev react-test-renderer#17.0.1 #testing-library/react-native #testing-library/jest-native
The current Jest configuration in the package.json file:
"jest": {
"preset": "react-native",
"coverageThreshold": {
"app/**/selectors.{js,ts,tsx}": {
"_comment": "Let's strive to increase coverage, instead of lowering it!",
"lines": 57
}
},
"coverageDirectory": ".coverage/",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"native"
],
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js|jsx)$",
"testPathIgnorePatterns": [
"\\.snap$",
"<rootDir>/node_modules/"
],
"cacheDirectory": ".jest/cache",
"setupFiles": [
"./jest.setup.js"
]
}
Seems nothing wrong with the component rendering but the test.
You can use getByText query which can be obtained from render.
Please refer to React Native Testing Library for more information.
import React from 'react';
import {render} from '#testing-library/react-native';
import Greetings from './Greetings';
describe('Greetings component', () => {
it('renders hello world as a test', () => {
const {getByText} = render(<Greetings hello="Hello World!" />);
expect(getByText('Hello World!')).toBeDefined();
});
});
The application was set up a while back and it seems they had mocked out the react-native imports in the jest.setup.js file so that was causing the issue

Jest test giving error “Cannot read property 'createElement' of undefined”

I have created a react app using nextjs (react 17.02 , next 11.1.0) and going to test a simple form using Jest and enzyme (jest 26.4.2, enzyme 3.11.0). When I import the .JSX file that I want to test in jest gives this error.
TypeError: Cannot read property 'createElement' of undefined
17 |
18 | const errorObj = {};
> 19 |
| ^
20 | if (meta && meta.touched && meta.error) {
21 | errorObj.error = true;
22 | errorObj.helperText = meta.error;
here is my jest.config.js file
module.exports = {
testPathIgnorePatterns: ["<rootDir>/.next/", "<rootDir>/node_modules/"],
setupFilesAfterEnv: ["<rootDir>/setupTests.js"],
moduleNameMapper: {
"\\.(css|less|scss|sass)$": "identity-obj-proxy"
},
transform: {
"^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
"\\.(css|less|scss|sass)$": "identity-obj-proxy"
}
};
Here is the signIn.test.js file
import SignIn from '../../../components/account/SignIn';
import sum from '../../../utilities/sample';
describe("Sum function test", () => {
test("should sum numbers", () => {
expect(sum(1,2)).toBe(3);
});
});
I’m getting above error after import my SignIn component. Without that test frameworks works fine.
What does that mean? Did I miss something?

Using React stroybook as Jest test

I have a React storybook and what to use it as my test cases
I have a "loader.js" that import all the stories
import sourceBasic from 'raw-loader!./Basics/foo.js?sourceMap';
import Basic from './Basics/foo';
const tree = {
Basics:[
{
title:'Creating and applying a style',
source:sourceBasic, element:Basic
},
{ .... }
],
[ .... ],
....
}
export default tree
I use the raw-loader and sourceMap to show the source with the element in storybook
This works great.
My problem is when I try to import with Jest
FAIL ./index.test.js
● Test suite failed to run
Cannot find module 'raw-loader!./Basics/foo.js?sourceMap' from 'load.js'
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
at Object.<anonymous> (example/stories/load.js:2:34)
The test file
import React from 'react';
import renderer from 'react-test-renderer';
import load from './example/stories/load'
for(const groupName in load ){
const groupArray = load[groupName];
describe(groupName, () => {
for(const item of groupArray ){
test(item.title, () => {
const elem = renderer.create(item.element);
expect(elem.toJSON()).toMatchSnapshot();
}) // END test
} // END for
}) // END describe
} // END for
Thanks for your help
UPDATE
The update and working stroybook as test is implemented on the project react-outline
You can clone it(react-outline), npm install and then npm test to see it in action.
Here is the output on travis :)
If you don't care about the raw-source and want to mock it. You can use the moduleNameMapper under your Jest setting within your package.json.
This will let you intercept all require/import based on a regex match.
Add to your package.json:
...
"dependencies": {
...
},
...
"jest": {
"globals": {
"__TEST__": true
},
"moduleNameMapper": {
"\\.(css|jpg|png)$": "<rootDir>/empty-module.js",
"^raw-loader": "<rootDir>/empty-module.js"
},
"testPathIgnorePatterns": [
"/node_modules/"
],
"verbose": true
}
}

Resources