我想知道如何嘲笑这种依赖的错误。如果我省略了这个导入并注释掉了相关的源代码,那么测试过程就会很好。已经通过了模拟函数Jest,但不知道我该做什么。
*该项目由CRA创建,并附有模板类型记录。
应用程序组件。
import { useAuthenticator } from '@aws-amplify/ui-react';
const App = () => {
const { user } = useAuthenticator((context) => [context.user]);
return (
<div>{user?.username}</div>
);
};
export default App;测试代码在这里。
import App from 'src/App';
import { render, screen } from '@testing-library/react';
describe('First group',()=>{
test('rendering App component',()=>{
// App includes 'import { useAuthenticator } from '@aws-amplify/ui-react';'
render(<App/>)
screen.debug()
})
})错误输出在这里。
● Test suite failed to run
TypeError: window.URL.createObjectURL is not a function
> 1 | import { useAuthenticator } from '@aws-amplify/ui-react';
| ^
2 |
3 | const App = () => {
4 | const { user } = useAuthenticator((context) => [context.user]);
at define (node_modules/maplibre-gl/dist/maplibre-gl.js:25:43)
at node_modules/maplibre-gl/dist/maplibre-gl.js:35:1
at node_modules/maplibre-gl/dist/maplibre-gl.js:3:81
at Object.<anonymous> (node_modules/maplibre-gl/dist/maplibre-gl.js:6:2)
at Object.<anonymous> (node_modules/@aws-amplify/ui-react/dist/index.js:1:484)
at Object.<anonymous> (src/App.tsx:1:1)根据幻灯片2的答案,添加了安装和配置文件。但还是会犯错误。两者都位于rootDir。
jest.setup.js
if (typeof window.URL.createObjectURL === 'undefined') {
window.URL.createObjectURL = jest.fn();
}jest.config.js
module.exports = {
setupFilesAfterEnv: ['./jest.setup.js'],
};更新
这个PJ是由CRA创建的,所以它需要遵循他们的规则。最后,我通过幻灯片说明2的答案和正确的位置来解决这个问题。
src/setupTests.ts
if (typeof window.URL.createObjectURL === 'undefined') {
window.URL.createObjectURL = jest.fn();
}发布于 2022-10-14 03:17:42
在包含Geo组件发布的v2.15.0 of @aws-amplify/ui-react中,Jest测试框架的用户在尝试运行测试时可能会遇到以下错误:
window.URL.createObjectURL is not a function请按照以下步骤解决此问题。
jest.setup.js
if (typeof window.URL.createObjectURL === 'undefined') {
window.URL.createObjectURL = jest.fn();
}jest.config.js
module.exports = {
//...
setupFilesAfterEnv: ['./jest.setup.js'],
//...
}当与使用未识别函数的包一起使用jsdom库(Jest的依赖项)时,这是一个已知的问题。见本期。
https://stackoverflow.com/questions/74063650
复制相似问题