Problem using jest with storybook snapshot testing in react native - react-native

What I have
I'm trying to use jest and Storybook with Storyshots addon for snapshot test in my react-native/typescript app, but I'm having some issues when I try to run simple test.
According to Snapshot testing section in storybook documentation, the only thing you need to do is create an storybook.test.js file with the following:
storybook.test.js
import initStoryshots from '#storybook/addon-storyshots';
initStoryshots();
After this, everything is supposed to work as expected, but the console throws the following error:
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to
import a file which Jest cannot parse, e.g.
it's not plain JavaScript.
By default, if Jest sees a Babel config,
it will use that to transform your files, ign
oring "node_modules".
Here's what you can do:
• If you are trying to use ECMAScript Mo
dules, see https://jestjs.io/docs/en/ecmascri
pt-modules for how to enable it.
• To have some of your "node_modules" fi
les transformed, you can specify a custom "tr
ansformIgnorePatterns" in your config.
• If you need a custom transformation sp
ecify a "transform" option in your config.
• If you simply want to mock your non-JS
modules (e.g. binary assets) you can stub th
em out with the "moduleNameMapper" config opt
ion.
You'll find more details and examples of
these config options in the docs:
https://jestjs.io/docs/en/configuration.h
tml
Details:
C:\Users\myuser\Desktop\myapp\node_m
odules\react-native-swipe-gestures\index.js:3
import React, { Component } from "react";
^^^^^^
SyntaxError: Cannot use import statement
outside a module
at Runtime.createScriptFromCode (node_m
odules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (node_modules/#st
orybook/react-native/dist/preview/components/
OnDeviceUI/navigation/index.js:29:53)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 11.468 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
jest.config.js
module.exports = {
preset: 'react-native',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
};
babel.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset']
};
If I remove #storybook/addon-storyshots relate things from my tests, everything is working normally without any problem. So I don't know if I need some extra configuration to make work storybook/jest snapshoot testing with react native.

It's enough. Add react-native-swipe-gestures to transformIgnorePatterns of your jest.config.js.
transformIgnorePatterns: ['node_modules/(?!(react-native|#react-navigation|#react-native|react-native-swipe-gestures)/)'],
This did a trick for me.

Related

SyntaxError: Cannot use import statement outside a module { AXIOS }

Hello I changed my code from fetch to axios and when I run my tests I get this problem... Can anyone help me with that ?
SyntaxError: Cannot use import statement outside a module
> 1 | import axios from "axios";
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
This issue occurred after axios update from 0.27.2 to 1.0.0. There is an opened issue, so probably this is going to be fixed soon. Meanwhile they're working on that, you can temporary fix it by setting up transformIgnorePatterns in jest config:
transformIgnorePatterns = ["node_modules/(?!axios)/"]
For me helped the following jest.config.js setup:
transformIgnorePattern: [
'<rootDir>/node_modules/(?!axios)/'
]
alongside with
moduleNameMapper: {
'^axios$': require.resolve('axios'),
}

Jest transformIgnorePatterns can't transpile vee-validate with pnpm

I have a Nuxt app that runs with pnpm and I'd like to test it using Jest and the vee-validate library.
Whenever I launch my tests, I get this error:
FAIL test/integration/components/ui/RegistrationForm.test.ts
● 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.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
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:
/my-project/node_modules/.pnpm/vee-validate#3.4.14_vue#2.6.14/node_modules/vee-validate/dist/rules.js:889
export { alpha, alpha_dash, alpha_num, alpha_spaces, between, confirmed, digits, dimensions, double, email, excluded, ext, image, integer, is, is_not, length, max, max_value, mimes, min, min_value, numeric, oneOf, regex, required, required_if, size };
^^^^^^
SyntaxError: Unexpected token 'export'
34 | } from '#nuxtjs/composition-api';
35 | import { extend, ValidationProvider } from 'vee-validate';
> 36 | import {
| ^
37 | min_value as minValue,
38 | max_value as maxValue,
39 | } from 'vee-validate/dist/rules';
at Runtime.createScriptFromCode (node_modules/.pnpm/jest-runtime#28.1.1/node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (components/form/fields/CalendarField.vue:36:1)
at Object.<anonymous> (components/form/fields/FormField.vue:14:1)
I tried to add the option transformIgnorePattern inside jest.config.js but it's not working at all.
This is what I tried:
transformIgnorePatterns: ['/node_modules/(?!vee-validate/dist/rules)']
transformIgnorePatterns: ['/node_modules/(?!(.*vee-validate/dist/rules))/']
The only option that works for me is to import the UMD build but I lose all the benefit of tree-shaking.
Sources
https://github.com/logaretm/vee-validate/issues/2310
https://github.com/facebook/jest/issues/2081#issuecomment-699558143
https://qiita.com/tamonmon/items/6392c1680ef498a8c816
I ran into the same problem and was able to fix it by adjusting my jest.config.js file. I did three things there:
add "vee-validate/dist/rules": "babel-jest", to transform: {}
add the file path to transformIgnorePatterns like this: transformIgnorePatterns: ["/node_modules/", "/components/views/*", "node_modules/vee-validate/dist/rules"],
add isolatedModules to true in ts-jest like: globals: {
"ts-jest": {
isolatedModules: true,
babelConfig: true,
},
},
Since this response is late to for the op, I hope this helps atleast someone :)

Jest doesnt recognize imported Styled Component from another library

React Native UI Library:
Written in TypeScript and Styled Components.
Written tests for the library using testing-library and jest.
All the tests pass.
React Native App:
Written in TypeScript and Styled Components.
This app imports the above UI Library.
Problem:
When I try to create a unit test for any component, I am getting the below error:
yarn run v1.22.17
$ node_modules/.bin/jest .
PASS src/__tests__/utilities.test.ts
FAIL src/components/shared/__tests__/logo.test.tsx
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/Users/USER/Projects/PROJECT/node_modules/hc-mobile-app-ui/dist/modules/accordion/accordion.js:47
return (<StyledWrapper testID="accordion">
^
SyntaxError: Unexpected token '<'
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (node_modules/hc-mobile-app-ui/dist/index.js:4:19)
Test Suites: 1 failed, 1 passed, 2 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 1.138 s
Ran all test suites matching /./i.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
What I Tried:
Installed jest-styled-components after I followed an article, but that didn't help.

React Native test with Jest and react-native-ble-plx library fails because "Jest encountered an unexpected token"

Trying to execute that must be a simple screen test, I found this error. I saw some related issues and solutions touching babel and jest config but I did not found the proper way to solve it.
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/Users/.../node_modules/react-native-ble-plx/index.js:3
export { BleError, BleErrorCode, BleAndroidErrorCode, BleIOSErrorCode, BleATTErrorCode } from './src/BleError'
^^^^^^
SyntaxError: Unexpected token 'export'
Any suggestion? Thanks!
Finally was solved adding it to jest.config.js:
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!(jest-)?#?react-native|#react-native-community|#react-navigation)',
],
Source: related issue on github
https://github.com/callstack/react-native-testing-library/issues/703

Webpack alias & config in Jest tests

I'm updating an older Webpack2 project to Webpack4 and switching the tests over to Jest but have a seemingly simple problem with a couple of the webpack related bits.
Specifically, the project structure for the troublesome bits look like this:
src
- constants
- index.js
- config
- base.js
- test.js
- dev.js
- dist.js
During testing, the classes under test use import config from 'config' so issue number one is allowing them to find the right config file. With Webpack2 this is subbed in by webpack itself, but obviously not during Jest tests.
I can resolve this by hard coding the specific test config into the moduleNameMapper in the jest config in package.json like so:
"jest": {
"moduleNameMapper": {
"^config$": "<rootDir>/src/config/test.js"
}
}
This appears to work.
The second part of my issue is allowing Jest to find named exports src/constants/index.js using syntax like import { SOME_CONST } from 'constants'.
When I try to use moduleNameMapper I get back undefined from anything that uses the constants and I believe this is because moduleNameMapper is largely used to mock out dependencies rather than supply them.
With this in mind I think I need to use modulePaths or moduleDirectories to allow the constants to be located.
I've tried the following configurations (not simultaneously) without any luck:
"modulePaths": [
"<rootDir>/src/constants",
"src/constants"
],
"moduleDirectories": [
"node_modules",
"src",
"src/constants",
"/src/constants"
"/src/constants/",
"./src/constants"
],
What should the correct config be for Jest to locate my constants?
If it's any help I'm trying to mimic this Webpack2 config in Jest
resolve: {
alias: {
constants: `${this.srcPathAbsolute}/constants/`
}
}