[英]"Cannot use import statement outside a module" error when importing react-hook-mousetrap in Next.js
[英]Next.js Cannot use import statement outside a module in third party library
概括
我正在使用 Next.js 创建 API 和前端应用程序。 前端使用反应。 对于单元测试,我使用next/jest
预设和 jest 作为单元测试库。 我正在使用@tenstack/react-query
进行 state 管理,当我想测试页面时,它会引发错误。 在我使用jsdom
环境的测试中,我添加了
/**
* @jest-environment jsdom
*/
在对 API 的测试中,我使用的是默认babel-jest
,不需要任何东西
抛出的错误
/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
错误出现在我想渲染使用react-query
页面的测试中
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
{
"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"
]
}
我已经尝试过这些答案,但不幸的是它没有帮助。
我通过 mocking library @tenstack/react-query
解决了自己的一个问题。 这是一个示例代码
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.