【问题标题】:How do I use jest to test a React component that imports a component that imports jQuery UI如何使用 jest 测试导入 jQuery UI 的组件的 React 组件
【发布时间】:2017-09-05 20:57:01
【问题描述】:

我正在尝试使用 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 中用于我的测试的内容,所以我认为我可以模拟出 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');

【问题讨论】:

    标签: jquery reactjs jquery-ui jestjs typescript2.0


    【解决方案1】:

    最简单的方法是像这样模拟ComponentB

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

    这会将ComponentB 在您的快照中呈现为&lt;ComponentB/&gt;。请注意,路径是相对于您的测试文件的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 2017-04-13
      • 2017-04-25
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多