我正在尝试使用react-addons-test-utils浅层渲染React组件(ComponentA),以便我可以对其进行快照。
组件 A 导入组件 B。
组件 B 导入“jquery”和“jquery-ui/ui/widgets/draggable”,这会在 Jest 下运行测试时导致错误:
jQuery 未定义
我尝试使用 package.json 中的 setupFiles 属性来导入 jquery 和 jquery UI,但仅部分成功。我收到此错误:无法读取未定义的属性“mouse”
因为我只想要一个浅层渲染,所以我并不真正关心测试中组件 B 中的内容,所以我想我也许能够模拟 jquery 和 jquery UI。但是,使用 jest.mock('jquery)
并不能修复 jQuery is not Defined
错误。
那么,上述方法是否可行,或者我是否需要完全走不同的路线?
示例代码:
ComponentA.tsx
import * as React from 'react';
import { AppState } from 'state/appState';
import { ComponentB } from 'components/b';
export class ComponentA extends React.Component<void, AppState> {
public render(): JSX.Element {
return (
<div>
<ComponentB/>
</div>
);
}
}
ComponentB.tsx
import * as React from 'react';
import * as $ from 'jquery';
import 'jquery-ui/ui/widgets/draggable';
export class ComponentB extends React.Component<{}, {}> {
// Lots of stuff with jQuery UI
}
Test.tsx
// Failed mocking of jquery
jest.mock('jquery');
jest.mock('jquery-ui/ui/widgets/draggable');
// Test file
import * as React from 'react';
import * as ReactTestUtils from 'react-addons-test-utils';
import { ComponentA } from 'components/a';
describe('ComponentA',
() => {
const shallowRenderer = ReactTestUtils.createRenderer();
it('renders correctly',
() => {
// Act
const tree = shallowRenderer.render(
<ComponentA/>
);
// Assert
expect(tree).toMatchSnapshot();
});
});
安装失败文件内容
var $ = require('jquery');
global.$ = global.jQuery = $;
require('jquery-ui');
最佳答案
最简单的方法是模拟 ComponentB
像这样
jest.mock('components/b', ()=> ({
ComponentB: () => 'ComponentB'
}))
这将渲染 ComponentB
如<ComponentB/>
在你的快照中。请注意,该路径是相对于您的测试文件的。
关于jquery - 如何使用 jest 测试导入 jQuery UI 组件的 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43329532/