我试图使用react-addons-test-utils浅呈现一个React组件(ComponentA),以便我可以快照它 .
组件A导入组件B.
组件B导入'jquery'和'jquery-ui/ui/widgets/draggable',这会在Jest下运行测试时导致错误: jQuery is not defined
我试图在package.json中使用setupFiles属性来导入jquery和jquery UI,只取得了部分成功 . 我得到这个错误: Cannot read property 'mouse' of undefined
因为我只想要一个浅层渲染我在组件B中为我的测试做了't really care what',所以我想我可以模拟出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();
});
});
Failed setupFile content
var $ = require('jquery');
global.$ = global.jQuery = $;
require('jquery-ui');
1 回答
最简单的方法是像这样嘲笑
ComponentB
这将在快照中将
ComponentB
渲染为<ComponentB/>
. 请注意,路径是相对于测试文件的 .