如何使用jest测试导入jQuery UI的组件的React组件

如何使用jest测试导入jQuery UI的组件的React组件,jquery,reactjs,jquery-ui,jestjs,typescript2.0,Jquery,Reactjs,Jquery Ui,Jestjs,Typescript2.0,我正在尝试使用react插件测试utils浅层呈现react组件(ComponentA),以便可以对其进行快照 组件A导入组件B 组件B导入“jquery”和“jquery ui/ui/widgets/DragTable”,这在Jest下运行测试时会导致错误: jQuery未定义 我尝试使用package.json中的setupFiles属性导入jquery和jquery UI,但仅部分成功。我发现了这个错误:无法读取未定义的属性“mouse” 由于我只需要一个浅层渲染,所以我并不真正关心测试组

我正在尝试使用react插件测试utils浅层呈现react组件(ComponentA),以便可以对其进行快照

组件A导入组件B

组件B导入“jquery”和“jquery ui/ui/widgets/DragTable”,这在Jest下运行测试时会导致错误:
jQuery未定义

我尝试使用package.json中的setupFiles属性导入jquery和jquery UI,但仅部分成功。我发现了这个错误:
无法读取未定义的属性“mouse”

由于我只需要一个浅层渲染,所以我并不真正关心测试组件B中的内容,所以我认为我可以模拟jquery和jquery UI。但是,使用
jest.mock('jquery)
无法修复
jquery未定义的错误

那么,上述两种方法是可行的,还是我需要走一条完全不同的路线

示例代码:

组件a.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>
        );
    }
}
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
}
// 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();
            });
    });

最简单的方法是像这样模拟
组件b

jest.mock('components/b', ()=> ({
  ComponentB: () => 'ComponentB'
}))
这将在快照中将组件B呈现为
。请注意,路径是相对于测试文件的

jest.mock('components/b', ()=> ({
  ComponentB: () => 'ComponentB'
}))