在嵌套的 React 组件中使用酶查找元素

Ala*_* P. 5 testing mocha.js reactjs enzyme

我正在尝试为我的组件编写一个,TestComponent以确保在用户单击按钮时触发回调。但是,未找到该按钮(尽管我可以通过调用 .html 在 HTML 中看到它)console.log(wrapper.html())

TestComponent如果重要的话,该按钮位于在 中使用的另一个组件内。

这是我的测试:

import React from 'react';
import expect from 'expect';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import TestComponent from './test-component.jsx';

describe('<TestComponent/>', () => {
  it('clicking "continue" button fires the callback', () => {
    const onClickContinue = sinon.spy();
    const wrapper = shallow(<TestComponent />);
    console.log(wrapper.find('.btn-primary').length); // 0
    console.log(wrapper.html());                      // does have `.btn-primary`

    // wrapper.find('.btn-primary').simulate('click');
    // expect(onClickContinue.calledOnce).toBe(true);
  });
});
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?谢谢你。

Ala*_* P. 8

弄清楚了。从https://facebook.github.io/react/docs/test-utils.html

浅渲染使您可以“深入一层”渲染组件并断言其渲染方法返回的内容,而无需担心未实例化或渲染的子组件的行为。

此测试需要使用子组件,因此必须使用mount代替shallow。这是工作代码:

import React from 'react';
import expect from 'expect';
import { mount } from 'enzyme';
import sinon from 'sinon';
import TestComponent from './test-component.jsx';

describe('<TestComponent/>', () => {
  it('clicking "continue" button fires the callback', () => {
    const wrapper = mount(<TestComponent />);
    const handleClickContinue = sinon.spy(wrapper.instance(), 'handleClickContinue');
    wrapper.find('.btn-primary').first().simulate('click');
    expect(handleClickContinue.calledOnce).toBe(true);
  });
});
Run Code Online (Sandbox Code Playgroud)

另请注意,我从 更改onClickContinuehandleClickContinue,因为此方法必须存在于组件中(而不是在 中调用的prop)。