Jest test error - Cannot find module meteor/tprzytula:remember-me - reactjs

I am using meteor/tprzytula:remember-me package in my Meteor React app.
I also use Jest for test automation.
I use the RememberMe component in my Signin form (a React functional component in Meteor)
When I try running tests with Jest I get the following error:
Cannot find module 'meteor/tprzytula:remember-me' from 'imports/ui/components/signin/SigninForm.js'
Require stack:
imports/ui/components/signin/SigninForm.js
tests/Signin.test.js
2 | import React, {useState, useRef} from 'react';
3 | import {Accounts} from 'meteor/accounts-base';
> 4 | import RememberMe from 'meteor/tprzytula:remember-me';
| ^
Here is my test code using Jest and Enzyme
tests/Signin.test.js
const wrapper = mount(<SigninForm />);
Update
I run my tests using npm test. Here is my entry on package.json
package.json
"test": "./node_modules/.bin/jest --verbose --silent",
Also adding my jest.config.js. Note I commented out moduleNameMapper. It errors out either way.
jest.config.js
module.exports = {
setupFiles: [
'./tests/setupTests.js',
],
transform: {
'^.+\\.jsx?$': 'babel-jest',
},
moduleFileExtensions: [
'js',
'jsx',
],
modulePaths: [
'<rootDir>/node_modules/',
'<rootDir>/node_modules/jest-meteor-stubs/lib/',
],
// moduleNameMapper: {
// 'meteor/tprzytula:remember-me': 'meteor/tprzytula:remember-me',
// '^(.*):(.*)$': '$1_$2',
// },
unmockedModulePathPatterns: [
'/^imports\\/.*\\.jsx?$/',
'/^node_modules/',
],
};
Is there a solution/workaround for this problem?

Related

Trying to test using jest but running into issues

Im trying to test a component using jest. The component imports spacetime npm module, which uses es-modules on main
https://www.npmjs.com/package/spacetime
I'm running into the following issues:
● 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:
/Users/wscott/dev/pm/client/node_modules/spacetime/src/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import Spacetime from './spacetime.js'
^^^^^^
SyntaxError: Cannot use import statement outside a module
6 | import search from '../../assets/images/search.svg';
7 | import Dropdown from 'react-bootstrap/Dropdown';
> 8 | import spacetime from "spacetime";
| ^
9 | import languages from "../../libraries/languages/language-list";
10 | import { Rating } from 'react-simple-star-rating';
11 |
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/components/Mentor/MentorList.js:8:1)
Here's my jest.config.js file
module.exports = {
preset: 'ts-jest',
transform: {
'^.+\\.(ts|tsx)?$': 'ts-jest',
"^.+\\.(js|jsx)$": "babel-jest",
".+\\.(css|styl|less|sass|scss)$": "jest-transform-css"
},
"moduleNameMapper": {
"\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/src/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/src//__mocks__/fileMock.js"
},
"setupFiles":["./src/browserMocks.js"],
"globals": {
"window": {
location: {
href: ""
},
localStorage: {
getItem: () => {
}
}
},
"localStorage": {
getItem: () => {
}
}
}
};
Here's my babel.config.js file:
module.exports = {
presets:[
"#babel/preset-env",
"#babel/preset-react"
],
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
}
}
Can someone help?
Downgrading to 6.12.3 fixes the issue with jest. The issue is space time use es-module imports which jest doesn't support but downgrading should work
Try to set the transformIgnorePatterns property to let jest transform the file before tests:
transformIgnorePatterns: [
'node_modules/(?!(spacetime)/)',
],
This way you are telling to skip transformation for all your node_modules except spacetime, which will be transformed by babel-jest as is set in you configuration.

getting jest to work with babel / laravel-mix

I'm using jest and testing-library/react for tests of my ReactJS components in a Laravel app.
My tests break because the component to to test isn't recognised by jest even after importing it into the test. I have the following settings in jest.config.js
module.exports = {
testRegex: 'resources/js/tests/.*.test.js$',
roots: ["<rootDir>/resources/js/"],
moduleDirectories: ["resources/js/components", "resources/js/containers", "resources/js/views", "node_modules"]
}
And in the package.json file
"test": "cross-env NODE_ENV=test jest",
Here's a simple test that fails due to error
import React from "react";
import { render, fireEvent, waitForElement } from "#testing-library/react";
import "#testing-library/jest-dom/extend-expect";
import axiosMock from "axios";
// the component to test
import BlogEditor from "../../components/BlogEditor/BlogEditor";
jest.mock("axios");
test("Blog Editor recieves props and renders", () => {
const { getByTestId } = render(
<BlogEditor
tags={[{ id: 1, name: "A tag"}]}
suggestions={[{id: 2, name: "A Suggestion"}]}
/>
);
});
The error I get is rather cryptic
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:
• 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:
SyntaxError: /Users/anadi/Code/adminpanel/resources/js/tests/BlogEditor/BlogEditor.test.js: Unexpected token (16:8)
14 | test("Blog Editor recived props and renders element", () => {
15 | const { getByTestId } = render(
> 16 | <BlogEditor
| ^
17 | tags={[{ id: 1, name: "A tag"}]}
18 | suggestions={[{id: 2, name: "A Suggestion"}]}
19 | />
at Parser.raise (node_modules/#babel/parser/src/parser/location.js:41:63)
at Parser.unexpected (node_modules/#babel/parser/src/parser/util.js:150:16)
at Parser.parseExprAtom (node_modules/#babel/parser/src/parser/expression.js:1123:20)
at Parser.parseExprSubscripts (node_modules/#babel/parser/src/parser/expression.js:529:23)
at Parser.parseMaybeUnary (node_modules/#babel/parser/src/parser/expression.js:509:21)
at Parser.parseExprOps (node_modules/#babel/parser/src/parser/expression.js:279:23)
at Parser.parseMaybeConditional (node_modules/#babel/parser/src/parser/expression.js:234:23)
at Parser.parseMaybeAssign (node_modules/#babel/parser/src/parser/expression.js:185:21)
at Parser.parseExprListItem (node_modules/#babel/parser/src/parser/expression.js:2077:18)
at Parser.parseCallExpressionArguments (node_modules/#babel/parser/src/parser/expression.js:817:14)
The problem was with my babel and jest configurations, moved jest configuration to package.json (I have no clue why this actually helped) but it did
"jest": {
"verbose": true,
"clearMocks": true,
"collectCoverage": true,
"testRegex" : "resources/js/tests/.*.test.js$",
"roots": ["<rootDir>/resources/js/"],
"moduleDirectories": ["resources/js/components", "resources/js/containers", "resources/js/views", "node_modules"],
"transform": {
"^.+\\.js$": "babel-jest"
},
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/resources/js/__mocks__/fileMock.js",
"\\.(css|scss)$": "<rootDir>/resources/js/__mocks__/styleMock.js"
}
and updated the babel configuration too
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-syntax-dynamic-import"
]
}

Jest SyntaxError: Unexpected token <

I'm want to test a component in a React app using Jest Enzyme with TypeScript. I follow the instructions on the Jest site, but for some reason I get:
SyntaxError: Unexpected token <
I can test test some functions. There isn't any problem with that, but when I use a component, I get an error.
This is the Jest configuration in file package.json:
"jest": {
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"testMatch": ["**/__tests__/*.(ts|tsx)"],
"snapshotSerializers": ["enzyme-to-json/serializer"],
"setupFilesAfterEnv": ["<rootDir>/src/setupEnzyme.ts"],
"unmockedModulePathPatterns": ["node_modules/react/", "node_modules/enzyme/"]
}
Enzyme configuration
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
export default class TesComponent extends Component {
render(){
return (
<div>test</div>
)
}
}
import { shallow } from 'enzyme'
import TestCompoenent from '../TestComponent'
test('component testing', () => {
const component = shallow(<TestCompoenent />)
expect(component.contains(<div>test</div>)).toBeTruthy()
})
This is the error:
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:
• 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:
/home/user/Documents/local-platform/frontend/src/pages/__tests__/settigs.test.tsx:9
var component = enzyme_1.shallow(<TestComponent_1.default />);
^
SyntaxError: Unexpected token <
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:471:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:513:25)
I expect for the tests to pass, because Test Component does include <div>test</div>.
Try changing tsconfig.json
"jsx": "preserve" -> "jsx": "react"
It seems that your configuration does not process the TypeScript file (.tsx) properly.
Here is part of my working configuration:
"jest": {
"transform": {
"^.+\\.tsx?$": "ts-jest",
},
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"json"
],
"setupTestFrameworkScriptFile": "<rootDir>/src/setupSpecs.ts"
}
I have used setupTestFrameworkScriptFile instead of setupFilesAfterEnv.

Unexpected token < in shallow in react typescript

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

Jest testing with React, Typescript and ES6

I'm having some issues testing a React component written in Typescript(v2.0.3) with Jest(v16.0.1) tests written in ES6.
I'm using the ts-jest(v0.1.8) preprocessor and the relevant part of my package.json looks like
"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/ts-jest/preprocessor.js",
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js"
]
}
But when I run the tests I get:
FAIL app/components/__tests__/TestTotalNumberOfTeapots.js
● Test suite failed to run
/Users/aaron/Desktop/teabot_stats/app/components/__tests__/TestTotalNumberOfTeapots.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React from 'react';
^^^^^^
SyntaxError: Unexpected token import
at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:284:10)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.673s
Ran all test suites.
My test looks like
import React from 'react';
import TotalNumberOfTeapots from '../TotalNumberOfTeapots.tsx';
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<TotalNumberOfTeapots numberOfTeapots='1' />
).toJSON();
expect(tree).toMatchSnapshot();
});
I assume I need to have a setup where my components are transpiled from Typescript to ES5 using ts-jest and my tests are transpiled from ES6 to ES5 using babel-jest before Jest reads them but I'm not sure how?
Managed to work this out, needed to write my own preprocessor:
const tsc = require('typescript');
const babelJest = require('babel-jest');
module.exports = {
process(src, path) {
if (path.endsWith('.ts') || path.endsWith('.tsx')) {
return tsc.transpile(
src,
{
module: tsc.ModuleKind.CommonJS,
jsx: tsc.JsxEmit.React,
},
path,
[]
);
}
if (path.endsWith('.js') || path.endsWith('.jsx')) {
return babelJest.process(src, path);
}
return src;
},
};
And update my package.json to have:
"jest": {
"scriptPreprocessor": "preprocessor.js",
"moduleFileExtensions": ["js", "jsx", "json", "ts", "tsx"]
},

Resources