MUI5 not working with jest - SyntaxError: Cannot use import statement outside a module
MUI5 not working with jest - SyntaxError: Cannot use import statement outside a module
可重现的回购:https://github.com/hutber/cannotusestatement
更令人担忧的是:https://codesandbox.io/s/vigilant-bartik-bmz8x 在沙箱中测试通过。但是,如果您检查上面导入到此沙箱中的 repo,它将不会在本地通过。
我毫不怀疑问题是我的笑话没有编译 运行 测试所需的 node_modules。但是我现在不知道如何让它工作。
我只是希望能够 运行 进行测试。他们目前运行
测试
import React from 'react'
import { renderWithThemeProvider, screen } from 'test-utils'
import { Select } from './Select'
it('renders correctly', () => {
const tree = renderWithThemeProvider(<Select id="testSelect"></Select>)
expect(tree).toMatchSnapshot()
})
jest.config.js
module.exports = {
roots: ['<rootDir>', './src'],
moduleDirectories: ['<rootDir>', 'node_modules/', './src'],
transform: {
'^.+\.(ts|tsx)$': 'ts-jest',
},
testEnvironment: 'jsdom',
testMatch: ['**/*.test.(ts|tsx)', '**/__tests__/*.(ts|tsx)'],
moduleNameMapper: {
// Mocks out all these file formats when tests are run
'\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': 'identity-obj-proxy',
'\.(css|less|scss|sass)$': 'identity-obj-proxy',
'app-config': '<rootDir>/app-config/default',
'^@components(.*)$': '<rootDir>/src/components',
'^@themes(.*)$': '<rootDir>/src/themes',
},
coverageThreshold: {
global: {
statements: 50,
},
},
}
babel.config.js
module.exports = {
presets: ['@babel/preset-env', '@babel/preset-react'],
env: {
test: {
presets: ['@babel/preset-env', '@babel/preset-react'],
plugins: [
[
'babel-plugin-transform-imports',
'@babel/plugin-proposal-class-properties',
'transform-es2015-modules-commonjs',
'babel-plugin-dynamic-import-node',
'babel-plugin-styled-components',
],
},
},
}
package.json
"test": "jest --watchAll=false",
纱线测试
(base) hutber@hutber:/var/www/target/component-library$ yarn test src/components/Select/Select.test.tsx
yarn run v1.22.17
$ jest --watchAll=false src/components/Select/Select.test.tsx
FAIL src/components/Select/Select.test.tsx
● 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:
/var/www/target/component-library/node_modules/@mui/material/styles/styled.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { createStyled, shouldForwardProp } from '@mui/system';
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import React from 'react'
> 2 | import styled from '@mui/material/styles/styled'
| ^
3 |
4 | import MuiSelect, { SelectProps as MuiSelectProps } from '@mui/material/Select'
5 | import InputLabel from '@mui/material/InputLabel'
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/components/Select/Select.tsx:2:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 3.272 s
import React from 'react'
import styled from '@mui/material/styles/styled'
import MuiSelect, { SelectProps as MuiSelectProps } from '@mui/material/Select'
import InputLabel from '@mui/material/InputLabel'
import MenuItem from '@mui/material/MenuItem'
import MuiFormControl from '@mui/material/FormControl'
interface ISelect extends MuiSelectProps {
id: string
label?: string
options?: { text: string; option: string }[]
}
const FormControl = styled(MuiFormControl)`
color: #fff;
border-radius: 30px;
width: 180px;
`
export const Select: React.FC<ISelect> = ({ label, id, children, options, ...props }) => {
return (
// @ts-ignore
<FormControl fullWidth hiddenLabel>
{label && (
<InputLabel id={`input_${id}`} shrink={false}>
{label}
</InputLabel>
)}
<MuiSelect id={id} {...props}>
{options && options.map(({ text, option }: { text: string; option: string }) => <MenuItem value={option}>{text}</MenuItem>)}
{children && children}
</MuiSelect>
</FormControl>
)
}
export default Select
首先,您的 Select.tsx
文件中有两个导出。使用默认导出即可,因此将第 20 行更改为:
const Select: React.FC<ISelect> = ({ label, id, children, options, ...props }) => {
然后在您的 Select.test.tsx
文件中更改为:
import Select from './Select'
最后要解决导入问题,请将 Select.tsx
中的代码更改为:
import { styled } from '@mui/material'
这是一个相当普遍的问题,可以看出 here。
可重现的回购:https://github.com/hutber/cannotusestatement
更令人担忧的是:https://codesandbox.io/s/vigilant-bartik-bmz8x 在沙箱中测试通过。但是,如果您检查上面导入到此沙箱中的 repo,它将不会在本地通过。
我毫不怀疑问题是我的笑话没有编译 运行 测试所需的 node_modules。但是我现在不知道如何让它工作。
我只是希望能够 运行 进行测试。他们目前运行
测试
import React from 'react'
import { renderWithThemeProvider, screen } from 'test-utils'
import { Select } from './Select'
it('renders correctly', () => {
const tree = renderWithThemeProvider(<Select id="testSelect"></Select>)
expect(tree).toMatchSnapshot()
})
jest.config.js
module.exports = {
roots: ['<rootDir>', './src'],
moduleDirectories: ['<rootDir>', 'node_modules/', './src'],
transform: {
'^.+\.(ts|tsx)$': 'ts-jest',
},
testEnvironment: 'jsdom',
testMatch: ['**/*.test.(ts|tsx)', '**/__tests__/*.(ts|tsx)'],
moduleNameMapper: {
// Mocks out all these file formats when tests are run
'\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': 'identity-obj-proxy',
'\.(css|less|scss|sass)$': 'identity-obj-proxy',
'app-config': '<rootDir>/app-config/default',
'^@components(.*)$': '<rootDir>/src/components',
'^@themes(.*)$': '<rootDir>/src/themes',
},
coverageThreshold: {
global: {
statements: 50,
},
},
}
babel.config.js
module.exports = {
presets: ['@babel/preset-env', '@babel/preset-react'],
env: {
test: {
presets: ['@babel/preset-env', '@babel/preset-react'],
plugins: [
[
'babel-plugin-transform-imports',
'@babel/plugin-proposal-class-properties',
'transform-es2015-modules-commonjs',
'babel-plugin-dynamic-import-node',
'babel-plugin-styled-components',
],
},
},
}
package.json
"test": "jest --watchAll=false",
纱线测试
(base) hutber@hutber:/var/www/target/component-library$ yarn test src/components/Select/Select.test.tsx
yarn run v1.22.17
$ jest --watchAll=false src/components/Select/Select.test.tsx
FAIL src/components/Select/Select.test.tsx
● 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:
/var/www/target/component-library/node_modules/@mui/material/styles/styled.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { createStyled, shouldForwardProp } from '@mui/system';
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import React from 'react'
> 2 | import styled from '@mui/material/styles/styled'
| ^
3 |
4 | import MuiSelect, { SelectProps as MuiSelectProps } from '@mui/material/Select'
5 | import InputLabel from '@mui/material/InputLabel'
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/components/Select/Select.tsx:2:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 3.272 s
import React from 'react'
import styled from '@mui/material/styles/styled'
import MuiSelect, { SelectProps as MuiSelectProps } from '@mui/material/Select'
import InputLabel from '@mui/material/InputLabel'
import MenuItem from '@mui/material/MenuItem'
import MuiFormControl from '@mui/material/FormControl'
interface ISelect extends MuiSelectProps {
id: string
label?: string
options?: { text: string; option: string }[]
}
const FormControl = styled(MuiFormControl)`
color: #fff;
border-radius: 30px;
width: 180px;
`
export const Select: React.FC<ISelect> = ({ label, id, children, options, ...props }) => {
return (
// @ts-ignore
<FormControl fullWidth hiddenLabel>
{label && (
<InputLabel id={`input_${id}`} shrink={false}>
{label}
</InputLabel>
)}
<MuiSelect id={id} {...props}>
{options && options.map(({ text, option }: { text: string; option: string }) => <MenuItem value={option}>{text}</MenuItem>)}
{children && children}
</MuiSelect>
</FormControl>
)
}
export default Select
首先,您的 Select.tsx
文件中有两个导出。使用默认导出即可,因此将第 20 行更改为:
const Select: React.FC<ISelect> = ({ label, id, children, options, ...props }) => {
然后在您的 Select.test.tsx
文件中更改为:
import Select from './Select'
最后要解决导入问题,请将 Select.tsx
中的代码更改为:
import { styled } from '@mui/material'
这是一个相当普遍的问题,可以看出 here。