I'm trying to test a Svelte component with Jest. This component works fine in the browser, but unit test fails with importing modules.
For example, when running Jest, import uuid from 'uuid' compiled as const { default: uuid } = require("uuid");, and calling uuid.v4() causes TypeError: Cannot read property 'v4' of undefined. When I use import * as uuid from 'uuid' or const uuid = require('uuid'), Jest unit test passes, but it doesn't work in the browser.
How can I deal with this issue? Any information would greatly help. Thank you.
package.json:
{
"name": "svelte-app",
"version": "1.0.0",
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "firebase serve --only hosting"
},
"devDependencies": {
"#rollup/plugin-json": "^4.0.0",
"#testing-library/jest-dom": "^5.1.1",
"#testing-library/svelte": "^1.11.0",
"bulma": "^0.8.0",
"eslint": "^6.7.0",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-jest": "^23.0.4",
"eslint-plugin-node": "^10.0.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"eslint-plugin-svelte3": "^2.7.3",
"jest-transform-svelte": "^2.1.1",
"node-sass": "^4.13.1",
"rollup": "^1.12.0",
"rollup-jest": "0.0.2",
"rollup-plugin-commonjs": "^10.0.0",
"rollup-plugin-livereload": "^1.0.0",
"rollup-plugin-node-builtins": "^2.1.2",
"rollup-plugin-node-globals": "^1.4.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-svelte": "^5.0.3",
"rollup-plugin-terser": "^5.1.2",
"sirv-cli": "^0.4.5",
"svelma": "^0.3.2",
"svelte": "^3.18.2",
"svelte-preprocess": "^3.4.0"
},
"dependencies": {
"firebase": "^7.8.2"
},
"private": true
}
rollup.config.js
import json from '#rollup/plugin-json'
import commonjs from 'rollup-plugin-commonjs'
import builtins from 'rollup-plugin-node-builtins'
import globals from 'rollup-plugin-node-globals'
import livereload from 'rollup-plugin-livereload'
import resolve from 'rollup-plugin-node-resolve'
import svelte from 'rollup-plugin-svelte'
import { terser } from 'rollup-plugin-terser'
import preprocess from 'svelte-preprocess'
const production = !process.env.ROLLUP_WATCH
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js',
},
plugins: [
// https://github.com/rollup/plugins/tree/master/packages/json
json(),
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file — better for performance
css: css => {
css.write('public/build/bundle.css')
},
preprocess: preprocess(),
}),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration —
// consult the documentation for details:
// https://github.com/rollup/rollup-plugin-commonjs
resolve({
browser: true,
dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/'),
}),
commonjs(),
globals(),
builtins(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser(),
],
watch: {
clearScreen: false,
},
}
function serve () {
let started = false
return {
writeBundle () {
if (!started) {
started = true
require('child_process').spawn('npm', ['run', 'start'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true,
})
}
},
}
}
jest.config.js
const sveltePreprocess = require('svelte-preprocess')
module.exports = {
displayName: { name: 'web', color: 'magentaBright' },
moduleFileExtensions: [
'js',
'json',
'svelte',
],
preset: 'rollup-jest',
transform: {
'\\.js$': 'rollup-jest',
'\\.svelte$': ['jest-transform-svelte', { preprocess: sveltePreprocess(), debug: true }],
},
setupFilesAfterEnv: ['#testing-library/jest-dom/extend-expect'],
}
It worked for me.
The issue seems like jest unable to resolve uuid while building the code at runtime.
Which is quite obvious because by default jest ignore node_modules packages.
I faced similar issues and resolved it. The approach is by configuration inform JEST that it has to include node_modules packages as well. In my project i used rollup-plugin-babel.
This is the babel plugin configuration
...
...
babel({
extensions: [ '.js', '.mjs', '.html', '.svelte' ],
runtimeHelpers: true,
exclude: [ 'node_modules/#babel/**', 'node_modules/core-js/**' ],
presets: [
[
'#babel/preset-env',
{
targets: '> 0.25%, not dead',
useBuiltIns: 'usage',
corejs: 3
}
]
]
})
And I've added babel-jest for transforming the jest.config.js
module.exports = {
preset: 'jest-puppeteer', //ignore the preset part, I used for puppeteer
transform: {
'^.+\\.js?$': require.resolve('babel-jest'),
"^.+\\.ts?$": "ts-jest" // this part is only required if you have typescript project
}
};
DO Not forget to install this packages like babel-jest, rollup-plugin-babel before using it.
I have been facing this same issue and have a work around by mocking the module in the test file and giving it a default key.
jest.mock('uuid', () => ({
default: {
v4: jest.fn(),
},
}))
Another way that seems to work is to destructure the import in the component file.
import { v4 as uuidv4 } from 'uuid'
Self answer:
Finally, I wrote a little preprocessor to replace import foo from 'foo' -> import * as foo from 'foo'
svelteJestPreprocessor.js
const svelteJestPreprocessor = () => ({
// replace `import foo from 'foo'` -> `import * as foo from 'foo'`
script: ({ content }) => ({
// process each line of code
code: content.split('\n').map(line =>
// pass: no import, import with {}, import svelte component
(!line.match(/\s*import/)) || (line.match(/{/)) || (line.match(/\.svelte/)) ? line
: line.replace(/import/, 'import * as'),
).join('\n'),
}),
})
module.exports = svelteJestPreprocessor
jest.config.js
const svelteJestPreprocessor = require('./svelteJestPreprocessor')
const sveltePreprocess = require('svelte-preprocess')
module.exports = {
moduleFileExtensions: [
'js',
'json',
'svelte',
],
preset: 'rollup-jest',
transform: {
'\\.js$': 'rollup-jest',
'\\.svelte$': ['jest-transform-svelte', {
preprocess: [
svelteJestPreprocessor(),
sveltePreprocess(),
],
}],
},
setupFilesAfterEnv: ['#testing-library/jest-dom/extend-expect'],
}
This is an unwanted workaround, but it works for now.
Related
I'm using rollup to bundle a library and I want to include external dependencies together with my code in the UMD bundle. I can't find any useful information about this in the docs. It could be that I'm missing something obvious but it seems like the docs only demonstrates how to mark relative modules as external. I've been trying to achieve this without any success. Is it doable and if yes, how?
My code making use of an external component: src/index.ts
import { ExternalComponent } from 'external-component'
function MyComponent() {
const externalComponent = ExternalComponent()
// ...
}
export default MyComponent
Desired output: bundle.umd.js
function ExternalComponent() {
// ...
}
function MyComponent() {
const externalComponent = ExternalComponent()
// ...
}
rollup.config.js
import babel from '#rollup/plugin-babel'
import typescript from 'rollup-plugin-typescript2'
import resolve from '#rollup/plugin-node-resolve'
import { terser } from 'rollup-plugin-terser'
import localTypescript from 'typescript'
const CONFIG_BABEL = {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
exclude: 'node_modules/**',
babelHelpers: 'bundled',
}
const CONFIG_TYPESCRIPT = {
tsconfig: 'tsconfig.json',
typescript: localTypescript,
}
const kebabCaseToPascalCase = (string = '') => {
return string.replace(/(^\w|-\w)/g, (replaceString) =>
replaceString.replace(/-/, '').toUpperCase(),
)
}
export default [
{
input: 'src/index.ts',
output: [
{
file: `${packageJson.name}.umd.js`,
format: 'umd',
strict: true,
sourcemap: false,
name: kebabCaseToPascalCase(packageJson.name),
plugins: [terser()],
}
],
plugins: [resolve(), typescript(CONFIG_TYPESCRIPT), babel(CONFIG_BABEL)],
},
]
package.json
{
"types": "index.d.ts",
"scripts": {
"build": "rollup -c",
"start": "rollup -c --watch",
},
"devDependencies": {
"#babel/core": "7.17.0",
"#rollup/plugin-babel": "^5.3.0",
"#rollup/plugin-node-resolve": "13.1.3",
"husky": "^4.3.8",
"npm-run-all": "^4.1.5",
"prettier": "2.5.1",
"rollup": "^2.67.0",
"rollup-plugin-terser": "^7.0.2",
"rollup-plugin-typescript2": "^0.31.2",
"typescript": "^4.5.5"
},
}
Thanks in advance,
David
I find something from the rollup documentation:
If you do want to include the module in your bundle, you need to tell Rollup how to find it. In most cases, this is a question of using #rollup/plugin-node-resolve.
But the #rollup/plugin-node-resolve doc does not help.
I followed the vite documentation for using library mode and I am able to produce a working component library.
I created the project with the vue-ts preset and in my component I have defined props with their types, and used some interfaces. But when I build the library, there are no types included.
How do I add types for the final build, either inferred from components automatically or manually with definition files?
More information
Here is some more information on my files:
tsconfig.json
{
"name": "#mneelansh/test-lib",
"private": false,
"version": "0.0.2",
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview"
},
"emitDeclarationOnly": true, // testing
"declaration": true, // testing
"main": "./dist/lib.umd.js",
"module": "./dist/lib.es.js",
"types": "./dist/main.d.ts",
"exports": {
".": {
"import": "./dist/lib.es.js",
"require": "./dist/lib.umd.js"
},
"./dist/style.css": "./dist/style.css"
},
"files": [
"dist"
],
"dependencies": {
"#types/node": "^17.0.25",
"vue": "^3.2.25"
},
"devDependencies": {
"#vitejs/plugin-vue": "^2.3.1",
"typescript": "^4.5.4",
"vite": "^2.9.5",
"vue-tsc": "^0.34.7"
}
}
I added the emitDeclarationOnly and declaration properties but that didn't help.
My vite.config.ts:
import { defineConfig } from "vite";
import vue from "#vitejs/plugin-vue";
const path = require("path");
// https://vitejs.dev/config/
export default defineConfig({
build: {
lib: {
entry: path.resolve(__dirname, "src/index.ts"),
name: "Button",
fileName: (format) => `lib.${format}.js`,
},
rollupOptions: {
external: ["vue"],
output: {
globals: {
vue: "Vue",
},
},
},
},
plugins: [vue()],
});
You can use vite-plugin-dts
import dts from "vite-plugin-dts";
export default defineConfig({
plugins: [
dts({
insertTypesEntry: true,
}),
],
Usually with vite and typescript project you need add type checking before build, because vite doesn't do it by himself. Here I'm also using vite-plugin-dts as in post from Julien Kode, and for type checking rollup-plugin-typescript2.
Finally my vite.config.js:
import { defineConfig } from 'vite';
import Vue from '#vitejs/plugin-vue2';
import dts from 'vite-plugin-dts';
import rollupTs from 'rollup-plugin-typescript2';
export default defineConfig({
plugins: [
Vue(),
dts({ insertTypesEntry: true }),
// only for type checking
{
...rollupTs({
check: true,
tsconfig: './tsconfig.json',
tsconfigOverride: {
noEmits: true,
},
}),
// run before build
enforce: 'pre',
},
],
build: {
sourcemap: true,
lib: {
entry: './src/index.ts',
fileName: 'index',
},
rollupOptions: {
// make sure to externalize deps that shouldn't be bundled
// into your library
external: [
'vue',
'vue-class-component',
'vue-property-decorator',
'vuex',
'vuex-class',
],
output: {
// Provide global variables to use in the UMD build
// for externalized deps
globals: {
vue: 'Vue',
},
},
},
},
});
You could write your own Vite plugin to leverage tsc at the buildEnd step to accomplish this. As other answers have suggested, you can use the flag emitDeclarationOnly.
See this simple example:
import { type Plugin } from 'vite';
import { exec } from 'child_process';
const dts: Plugin = {
name: 'dts-generator',
buildEnd: (error?: Error) => {
if (!error) {
return new Promise((res, rej) => {
exec('tsc --emitDeclarationOnly', (err) => (err ? rej(err) : res()));
});
}
},
};
Then add to your plugins field of your vite config
Personally I think a nicer way to do it is with vue-tsc:
vue-tsc --declaration --emitDeclarationOnly
See https://stackoverflow.com/a/70343443/398287
I have extensive applications in svelte, later I need to attach a sapper to it for further work, it is possibly? I try do it via:
npm i #sapper
but when I try to import something from this package e.q.:
import { goto } from '#sapper/app';
compiler throw me that i have no dependency to this sapper methods :(
I have no idea how to attach sapper to my project
my rollup
import svelte from "rollup-plugin-svelte";
import resolve from "#rollup/plugin-node-resolve";
import commonjs from "#rollup/plugin-commonjs";
import livereload from "rollup-plugin-livereload";
import { terser } from "rollup-plugin-terser";
// library that helps you import in svelte with
// absolute paths, instead of
// import Component from "../../../../components/Component.svelte";
// we will be able to say
// import Component from "components/Component.svelte";
import alias from "#rollup/plugin-alias";
const production = !process.env.ROLLUP_WATCH;
// configure aliases for absolute imports
const aliases = alias({
resolve: [".svelte", ".js"], //optional, by default this will just look for .js files or folders
entries: [
{ find: "components", replacement: "src/components" },
{ find: "views", replacement: "src/views" },
{ find: "assets", replacement: "src/assets" },
],
});
function serve() {
let server;
function toExit() {
if (server) server.kill(0);
}
return {
writeBundle() {
if (server) return;
server = require("child_process").spawn(
"npm",
["run", "start", "--", "--dev"],
{
stdio: ["ignore", "inherit", "inherit"],
shell: true,
}
);
process.on("SIGTERM", toExit);
process.on("exit", toExit);
},
};
}
export default {
input: "src/main.js",
output: {
sourcemap: true,
format: "iife",
name: "app",
file: "public/build/bundle.js",
},
plugins: [
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file - better for performance
css: (css) => {
css.write("bundle.css");
},
}),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ["svelte"],
}),
commonjs(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload("public"),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser(),
// for absolut imports
// i.e., instead of
// import Component from "../../../../components/Component.svelte";
// we will be able to say
// import Component from "components/Component.svelte";
aliases,
],
watch: {
clearScreen: false,
},
};
my package.json:
{
"name": "svelte-app",
"version": "1.0.0",
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv public -s",
"build:tailwind": "tailwind build public/assets/styles/index.css -o public/assets/styles/tailwind.css",
"build:fontawesome": "mkdir -p public/assets/vendor/#fortawesome/fontawesome-free/webfonts && mkdir -p public/assets/vendor/#fortawesome/fontawesome-free/css && cp -a ./node_modules/#fortawesome/fontawesome-free/webfonts public/assets/vendor/#fortawesome/fontawesome-free/ && cp ./node_modules/#fortawesome/fontawesome-free/css/all.min.css public/assets/vendor/#fortawesome/fontawesome-free/css/all.min.css",
"install:clean": "rm -rf node_modules/ && rm -rf package-lock.json && rm -rf public/build && npm install && npm run build:tailwind && npm run build:fontawesome && npm run dev"
},
"devDependencies": {
"#rollup/plugin-commonjs": "^16.0.0",
"#rollup/plugin-node-resolve": "^10.0.0",
"rollup": "^2.3.4",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-css-only": "^3.1.0",
"rollup-plugin-livereload": "^2.0.0",
"rollup-plugin-node-polyfills": "^0.2.1",
"rollup-plugin-svelte": "^7.0.0",
"rollup-plugin-terser": "^7.0.0",
"svelte": "^3.0.0",
"webpack": "^5.11.1",
"webpack-cli": "^4.3.1"
},
"dependencies": {
"#fortawesome/fontawesome-free": "5.14.0",
"#popperjs/core": "2.5.1",
"#rollup/plugin-alias": "3.1.1",
"#rollup/plugin-replace": "^2.3.4",
"#tailwindcss/custom-forms": "0.2.1",
"body-parser": "^1.19.0",
"chart.js": "2.9.3",
"compression": "^1.7.4",
"express": "^4.17.1",
"express-session": "^1.17.1",
"fontawesome-svelte": "^2.0.1",
"node-fetch": "^2.6.1",
"node-sass": "^5.0.0",
"page": "^1.11.6",
"polka": "^0.5.2",
"rollup-plugin-scss": "^2.6.1",
"session-file-store": "^1.5.0",
"sirv": "^1.0.10",
"sirv-cli": "1.0.6",
"svelte-routing": "1.4.2",
"tailwindcss": "1.8.10"
}
}
I was looking for this answer, I think the #Romain Durand answer is the closest, I don't think we can add ssaper to an existing svelte project. I would have to initialize project in ssaper and use svelte.
I'm kind of new to testing library, and recently started studying Jest. I'm currently trying to implement vanilla javascript project with jest.
I know 'mocking' an async API call in jest is best practice, but I wanted to actually call API using fetch to see if jest works correctly. But I got stuck on 'fetch' request. Need to remind you that my project is not node project, just plain vanilla javascript project.
Before moving on to actual test code, since I'm using babel and webpack on my project. Here's .bablerc.js and webpack.config.js implementation.
.babelrc.js
module.exports = {
presets: [
[
'#babel/env',
{
targets: {
browsers: ['> 0.25%, not dead'],
},
useBuiltIns: 'usage',
corejs: 3,
shippedProposals: true,
},
],
],
};
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'development',
entry: './src/js/index.js',
output: {
path: path.resolve(__dirname, 'public'),
filename: 'static/js/main.js',
},
module: {
rules: [
{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/,
},
{
test: /\.(sc|c)ss$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
],
},
devServer: {
contentBase: path.resolve(__dirname, 'public'),
inline: true,
hot: true,
watchOptions: {
poll: true,
ignored: '/node_modules/',
},
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Typing Game',
minify: {
collapseWhitespace: true,
},
hash: true,
template: './src/index.html',
}),
new MiniCssExtractPlugin({ filename: 'static/css/styles.css' }),
],
};
With project configuration above, webpack and webpack-dev-server worked perfectlly and could retrieve completely built html, css and js files. After checking everything except Jest works perfectly, I implemented simple API call function that gets list of words in array,
export const getWordsAPI = () =>
fetch(
'https://server-api-address'
).then((res) => res.json());
And tried to call the api function on my jest test code.
import { getWordsAPI } from '../src/js/api';
describe('Integration with getWords API', () => {
test('Get Word List', async () => {
const result = await getWordsAPI();
expect(result).toEqual([
{
text: 'hello',
},
{
text: 'world',
}
]);
});
});
But, I continuously got this 'fetch is not defined' error.
ReferenceError: fetch is not defined
> 1 | export const getWordsAPI = () =>
| ^
2 | fetch(
3 | 'https://server-api-address'
4 | ).then((res) => res.json());
at getWordsAPI (src/js/api.js:1:28)
at _callee$ (__tests__/api.test.js:5:26)
at tryCatch (node_modules/regenerator-runtime/runtime.js:63:40)
at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:293:22)
at Generator.next (node_modules/regenerator-runtime/runtime.js:118:21)
at asyncGeneratorStep (__tests__/api.test.js:11:103)
at _next (__tests__/api.test.js:13:194)
at __tests__/api.test.js:13:364
at Object.<anonymous> (__tests__/api.test.js:13:97)
I tried everything to solve this problem, including jest-fetch-mock but couldn't solve the problem. when I applied jest-fetch-mock to test code, I got new error which is this.
invalid json response body at reason unexpected end of json input
I eventually ended up using isomorphic-fetch library to make fetch work on my test code, which makes me uncomfortable.
import 'isomorphic-fetch';
import { getWordsAPI } from '../src/js/api';
describe('Integration with getWords API', () => {
...
}
I understand fetch is not defined error happening on nodejs environment, since there is not fetch provided by node, but this is vanilla javascript project. fetch is provided by default on browser, and should work without any additional work. But why is this error happening? I don't know what is causing this problem, either babel or webpack or even jest itself.
Please teach me what I'm missing. Probably I'm missing the main concept of Jest architecture, related to this problem. Waiting for anyone's response
ps. In case you need to know what version of libraries I'm using in my project, here's my package.json file. Other than libraries, I'm using WSL2 on Windows OS, and using npm instead of yarn.
{
"name": "typing_game",
"version": "1.0.0",
"description": "Typing Game by Vanilla Javascript",
"main": "index.js",
"author": "piecemakerz <piecemakerz#naver.com>",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --open",
"build": "webpack",
"test": "jest"
},
"devDependencies": {
"#babel/core": "^7.12.3",
"#babel/preset-env": "^7.12.1",
"#types/jest": "^26.0.15",
"babel-jest": "^26.6.3",
"babel-loader": "^8.2.1",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^5.0.1",
"html-webpack-plugin": "^4.5.0",
"jest": "^26.6.3",
"mini-css-extract-plugin": "^1.3.1",
"prettier": "^2.1.2",
"sass-loader": "^10.1.0",
"webpack": "^4.44.2",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"core-js": "^3.7.0",
"isomorphic-fetch": "^3.0.0",
"sass": "^1.29.0"
},
"jest": {
"transform": {
"^.+\\.js?$": "babel-jest"
}
}
}
I have the following Jest test:
import React from 'react';
import IndexSign from '../IndexSign';
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<IndexSign index={1}/>
).toJSON();
expect(tree).toMatchSnapshot();
});
The IndexSign component that I am calling calls this StyleSheet component:
import {StyleSheet} from 'react-native';
export default StyleSheet.create({
//some styles
});
For testing, I am using Gulp:
gulp.task('tests', () => {
process.env.NODE_ENV = 'test';
return gulp.src('src').pipe(jest({
}));
});
The problem is that when I run this test, I get:
● Test suite failed to run
Cannot find module 'StyleSheet' from 'react-native-implementation.js'
at Resolver.resolveModule (../node_modules/jest-resolve/build/index.js:142:17)
at Object.StyleSheet (../node_modules/react-native/Libraries/react-native/react-native-implementation.js:98:25)
at Object.<anonymous> (styles/Styles.js:5:13)
Any idea why this is happening?
Why is it searching for StyleSheet in react-native-implementation.js rather than react-native, which I imported?
And why can it not find StyleSheet?
I ran into the same issue. Adding
"jest": {
"preset": "react-native"
},
in the package.json fixed the error for me.
Incase you are keeping separate config file like jest.config.js. Add preset in it. Checkout the sample config file
module.exports = {
preset: 'react-native',
setupFiles: ['<rootDir>/__test__/setup.js'],
moduleNameMapper: {
'\\.(css|less)$': 'identity-obj-proxy',
'^.+\\.(jpg|jpeg|gif|png|mp4|mkv|avi|webm|swf|wav|mid)$': 'jest-static-stubs/$1'
},
globals: {
__DEV__: true
},
collectCoverageFrom: [
'**/src/**/*.{js,jsx}',
'!**/src/**/style.js',
'!**/src/**/index.js',
'!**/src/theme/**',
'!**/android/**',
'!**/ios/**',
'!**/node_modules/**',
'!**/scripts/**',
'!**/__test__/**'
],
verbose: true,
testPathIgnorePatterns: ['/node_modules/'],
testResultsProcessor: 'jest-sonar-reporter',
testURL: 'http://localhost/'
}
There are two ways of fixing this issue.
1. Make sure you don't have or delete any file called jest.config.js in your root folder.
2. If you want to have a custom jest.config.js file, make sure you have a preset node in it.
Like so:
module.exports = {
preset: "react-native",
verbose: true,
};
I was facing the same problem. Now it is resolved.
My package.json looks like this :
{
"name": "ReactNativeTDDStarterKit",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.8.3",
"react-native": "0.59.5"
},
"devDependencies": {
"#babel/core": "7.4.4",
"#babel/runtime": "7.4.4",
"babel-jest": "24.8.0",
"babel-preset-flow": "^6.23.0",
"babel-preset-react-native": "4.0.0",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"enzyme-to-json": "^3.3.1",
"jest": "24.8.0",
"metro-react-native-babel-preset": "0.54.0",
"react-dom": "^16.8.6",
"react-test-renderer": "16.8.3"
},
"jest": {
"preset": "react-native",
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"setupFiles": [
"<rootDir>/jest/setup.js"
]
}
}
I am using react-native 0.59.5, I did not reset .babelrc or jest.config.js manually, I just installed the dependencies. It automatically generated presets for me after the installation is completed. My babel.config.js looks like :
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
};
I followed instructions from this Link