[英]Next.js Cannot use import statement outside a module in third party library
Summary概括
I'm using Next.js to create both API and and Frontend app.我正在使用 Next.js 创建 API 和前端应用程序。 Frontend uses react.
前端使用反应。 To unit testing I'm using
next/jest
preset and jest as an unit testing library.对于单元测试,我使用
next/jest
预设和 jest 作为单元测试库。 I'm using @tenstack/react-query
to state management and when I want to test page, it throws an error.我正在使用
@tenstack/react-query
进行 state 管理,当我想测试页面时,它会引发错误。 In tests where I'm using jsdom
environment I add在我使用
jsdom
环境的测试中,我添加了
/**
* @jest-environment jsdom
*/
in tests to API I'm using babel-jest
that is default and no need anything在对 API 的测试中,我使用的是默认
babel-jest
,不需要任何东西
error that throws抛出的错误
/path/to/project/node_modules/@tanstack/react-query/src/QueryClientProvider.tsx:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import * as React from 'react'
^^^^^^
SyntaxError: Cannot use import statement outside a module
The error appers in test where I want to render page that uses react-query
错误出现在我想渲染使用
react-query
页面的测试中
jest.config.js jest.config.js
// jest.config.js
const nextJest = require('next/jest');
const createJestConfig = nextJest({
dir: './'
});
const customJestConfig = {
moduleDirectories: ['node_modules', '<rootDir>/'],
transform: {
'^.+\\.[t|j]sx?$': 'ts-jest'
}
};
module.exports = createJestConfig(customJestConfig);
.babelrc .babelrc
{
"presets": ["next/babel","@babel/preset-env", "@babel/preset-typescript"],
"plugins": [
"babel-plugin-transform-typescript-metadata",
["@babel/plugin-proposal-decorators", { "legacy": true }],
"babel-plugin-parameter-decorator"
]
}
I've tried these answers but unfortunatelly it didn't help.我已经尝试过这些答案,但不幸的是它没有帮助。
I solved myself an issue by mocking library @tenstack/react-query
.我通过 mocking library
@tenstack/react-query
解决了自己的一个问题。 Here is an sample code这是一个示例代码
jest.mock('@tanstack/react-query/src/QueryClientProvider', () => ({
QueryClientProvider: ({ children }) => children
}));
jest.mock('@tanstack/react-query', () => ({
QueryClient: jest.fn(),
useQueryClient: jest.fn(),
useQuery: jest.fn(),
useMutation: jest.fn().mockReturnValue({
mutate: jest.fn(),
isLoading: false
})
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.