jest with typescript throws an error when importing a file - reactjs

I'm having issues with jest on typescript.
//myprovider.tsx
class MyProvider{
constructor(){}
giveMeFive(): int{ return 5; }
}
export { MyProvider }
// myprovider.test.js
import { MyProvider } from './myprovider';
test('give me five!', () => {
const myprovider = new MyProvider();
/// assert
})
I get the following 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".
import { MyProvider } from './myprovider';
^
I'm not sure what I'm missing, I have this on my package
//package.json
"jest": {
"transform": {
".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "(/tests/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"moduleFileExtensions": ["ts", "tsx", "js"]
},
// .babelrc
{
"presets": [
"#babel/preset-typescript"
]
}
//jest.config.js
module.exports = {
preset: 'ts-jest',
transform: {
'^.+\\.tsx?$': 'babel-jest',
},
}

Make sure to install these packages:
babel-jest #babel/core #babel/preset-env
Your babel config should look like this:
presets: [
[
"#babel/preset-env",
{
targets: {
node: "current",
},
},
],
"#babel/preset-typescript",
]

Related

Jest import issue for react js app with custom imports prefix for workerize-loader

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;
};
`;
}
};

Next js jest coverage

I am using in my next js application Cypress and Jest. Running jest --coverage i get an error:
STACK: Error: Duplicate plugin / preset detected.
If you 'd like to use two separate instances of a plugin,
they need separate names, e.g.
plugins: [
['some-plugin', {}],
['some-plugin', {}, 'some unique name'],
]
This is my .babelrc file:
{
"presets": ["next/babel"],
"plugins": ["istanbul"]
}
Who faced with the same issue and how to solve it to get the coverage?
I found the solution that helped to solve the problem.
I had to add the env variable to the .babelrc
{
"env": {
"component": {
"plugins": [
"istanbul"
]
}
}
}
Then add it to cypress.config.js
const { defineConfig } = require('cypress');
const { devServer } = require('#cypress/webpack-dev-server');
const webpackConfig = require('./config/cypress.webpack.config.js');
const codeCoverageTask = require('#cypress/code-coverage/task');
module.exports = defineConfig({
viewportWidth: 1000,
viewportHeight: 660,
video: false,
env: {
BABEL_ENV: 'component',
},
component: {
devServer(devServerConfig) {
return devServer({
...devServerConfig,
framework: 'react',
webpackConfig,
});
},
specPattern: 'src/**/*.cy.{js,ts,jsx,tsx}',
setupNodeEvents(on, config) {
codeCoverageTask(on, config);
return config;
},
},
});

Twin Macro can't get daisyui (tailwind's plugin) class on NX workspace project

I'm creating project with nx, and also use nx preset to setup the project,and I tried to add some ready-to-go UI lib, adding tailwind first, then adding 'daisyui' the tailwind components. But I got the issue that seems macro can't find daisyui class. for normal tailwind class it's working properly.
if you need more context and file config that I'm missing to show here, please tell me. thankyou for all your helps.
Error:
ERROR in ./src/app/app.tsx
Module build failed (from ../../node_modules/#nrwl/web/src/utils/web-babel-loader.js):
MacroError: path/on/my/machine/mono-repo/apps/appname/src/app/app.tsx:
✕ btn was not found
btn is button className on daisyui component.
How I use twin macro
import styled from "#emotion/styled"
import tw from "twin.macro"
...
const StyledButton = styled.button`
${tw`btn btn-primary`}
`
.babelrc
{
"presets": [
[
"#nrwl/react/babel",
{
"runtime": "automatic",
"targets": {
"browsers": [">0.25%", "not dead"]
}
}
],
"#emotion/babel-preset-css-prop",
"#babel/preset-typescript"
],
"plugins": [
"babel-plugin-transform-inline-environment-variables",
["babel-plugin-twin", { "debug": true }],
"babel-plugin-macros",
[
"#emotion/babel-plugin-jsx-pragmatic",
{
"export": "jsx",
"import": "__cssprop",
"module": "#emotion/react"
}
],
[
"#babel/plugin-transform-react-jsx",
{
"pragma": "__cssprop",
"pragmaFrag": "React.Fragment"
}
]
]
}
and project.json setup config
{
"root": "apps/appname",
"sourceRoot": "apps/appname/src",
"projectType": "application",
"targets": {
"build": {
"executor": "#nrwl/web:webpack",
"outputs": ["{options.outputPath}"],
"defaultConfiguration": "production",
"options": {
"compiler": "babel",
....others config ....
"styles": ["apps/sandbox/src/styles.scss"],
"scripts": [],
"webpackConfig": "apps/sandbox/webpackConfig.js"
},
...
}
...
}
my webpackConfig.js
const webpack = require("webpack")
const nrwlConfig = require("#nrwl/react/plugins/webpack.js")
const webpackTailwindConfig = require("./webpack-tailwind.config")
module.exports = (config, env) => {
config = nrwlConfig(config)
return {
...config,
...other config ..
module: {
...config.module,
rules: [...config.module.rules, webpackTailwindConfig.tailwindWebpackRule]
},
node: { ...config.node, global: true }
}
}
webpack-tailwind.config
const tailwindWebpackRule = {
test: /\.scss$/,
loader: "postcss-loader"
}
exports.tailwindWebpackRule = tailwindWebpackRule
and style.scss that import all tailwind
#import "tailwindcss/base";
#import "tailwindcss/components";
#import "tailwindcss/utilities";

Cannot find module error while import using jest in next.js

I am trying to configure Jest in my Next.js project. In my test file, I have imported my component like import { HamburgerMenu } from './HamburgerMenu.jsx'. In that component, there are so many other imports. Once of them is
import {
checkValidEmail, getNumbers, getFormttedPhoneNo, validateSubscription,
} from 'helpers/utils';
When I run tests, it gives me the following error (which is on above import statement):
Cannot find module 'helpers/utils' from 'components/common/Smart/HamburgerMenu/HamburgerMenu.jsx'
So here are the details.
jest.config.js (at root dir)
module.exports = {
collectCoverageFrom: [
'**/*.{js,jsx,ts,tsx}',
'!**/*.d.ts',
'!**/node_modules/**',
],
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testPathIgnorePatterns: ['/node_modules/', '/.next/'],
transform: {
'^.+\\.(js|jsx|ts|tsx)$': '<rootDir>/node_modules/babel-jest'
},
transformIgnorePatterns: [
'/node_modules/',
'^.+\\.module\\.(css|sass|scss)$',
],
moduleNameMapper: {
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
},
}
I have added jest: true in the ESLint file.
babel.config.js file (at root dir):
module.exports = {
presets: ["next/babel"],
plugins: [["babel-plugin-styled-components", { ssr: true }]]
};
You can try to add
...
moduleDirectories: ['node_modules', '.'],
...
to your jest.config.js

How to debug React jest enzyme test cases

When am trying to debug Rect Jest enzyme test cases in terminal, am getting the following error and am stuck because of that.
I created the app using create-react-app and following is my configuration:
.babelrc
{
"env": {
"test": {
"sourceMaps": "inline",
"presets": ["es2015", "react-app"],
"plugins": ["transform-export-extensions"],
"only": [
"./**/*.js",
"node_modules/jest-runtime"
]
}
}
}
Jest config from package.json
"jest": {
"testMatch": [
"**/src/**/?(*.)(spec|test).js?(x)"
],
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"moduleFileExetnsions": [
"ts",
"txx",
"js",
"json"
],
"transform": {
"^.+\\.jsx$": "babel-jest",
"^.+\\.js$": "babel-jest"
}
}
Test case:
import { shallow } from 'enzyme';
import App from './App';
describe('App', () => {
it('should render app', () => {
const component = shallow(<App />);
expect(component).toMatchSnapshot();
});
});
Getting the following error:
Test suite failed to run
ReferenceError: [BABEL] .../src/containers/App.spec.js: Unknown option: /node_modules/babel-preset-react-app/index.js.overrides. Check out http://babeljs.io/docs/usage/options/ for more information about options.
A common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:
Invalid:
`{ presets: [{option: value}] }`
Valid:
`{ presets: [['presetName', {option: value}]] }`
For more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options. (While processing preset: "/node_modules/babel-preset-react-app/index.js")
at Logger.error (node_modules/babel-core/lib/transformation/file/logger.js:41:11)
at OptionManager.mergeOptions (node_modules/babel-core/lib/transformation/file/options/option-manager.js:226:20)
at node_modules/babel-core/lib/transformation/file/options/option-manager.js:265:14
at node_modules/babel-core/lib/transformation/file/options/option-manager.js:323:22
at Array.map (<anonymous>)
at OptionManager.resolvePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
at OptionManager.mergePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
at OptionManager.mergeOptions (node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
at OptionManager.init (node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
at File.initOptions (node_modules/babel-core/lib/transformation/file/index.js:212:65)
Edit:
Above error gone after changing "test" --> "dev" in .babelrc, but getting the another error:
"Jest encountered an unexpected token" at shallow(< App debug / >);
Try to use this .babel config:
{
"presets": ["es2015", "react-app"],
"plugins": ["transform-export-extensions"],
"only": [
"./**/*.js",
"node_modules/jest-runtime"
]
}
It should help you.

Categories

Resources