用玩笑和酶手动模拟嵌套的React组件

时间:2018-11-06 10:08:33

标签: reactjs mocking jestjs enzyme

我正在测试OuterComponent的{​​{1}}触发某些函数调用时是否行为正确。简化示例:

InnerComponent

由于// js/OuterComponent.js onInput() { // Behaviour to test } render() { return ( <div> <InnerComponent onInput={() => this.onInput()} /> </div> ); } 最终要调用InnerComponent必须发生一系列复杂的事件,因此我想在测试中模拟this.props.onInput()。我正在尝试执行以下操作:

InnerComponent

模拟:

// tests/OuterComponent.test.js

jest.useFakeTimers();

describe("OuterComponent", () => {
  test("behaves correctly when receiving input", () => {
    jest.mock("../js/InnerComponent")
    const wrapper = shallow(<OuterComponent />);
    jest.runAllTimers();
    // expectations about OuterComponent after `onInput` has been called
  });
});

我的// js/__mocks__/InnerComponent.js export default class SVGSymbolDrawing extends React.Component { componentDidMount() { setTimeout(() => { this.props.onInput(); }, 100); } render() { return <div/>; } } 都失败了。我从InnerComponent模拟中看不到任何console.logs,但是我不确定如何使用模拟而不是真正的内部组件来测试它。

1 个答案:

答案 0 :(得分:0)

您可以直接使用wrapper.instance().onInput()调用此函数,而不是模拟整个InnerComponent,即调用import React, { Component } from "react"; import InnerComponent from "./InnerComponent"; class OuterComponent extends Component { onClick() { this.setState({ clicked: true }); } render() { return <InnerComponent onClick={() => this.onClick()} />; } } export default OuterComponent;

通过测试的完整示例:

OuterComponent.js

const InnerComponent = ({onClick}) => <div onClick={onClick}>INNER</div>;
export default InnerComponent;

InnerComponent.js

import React from "react";
import Enzyme, { shallow } from "enzyme";
import Adapter from 'enzyme-adapter-react-16';
import OuterComponent from "./OuterComponent.js";

Enzyme.configure({ adapter: new Adapter() });

describe("OuterComponent", () => {
  it("handles onClick", () => {
    const wrapper = shallow(<OuterComponent />);
    wrapper.instance().onClick();
    expect(wrapper.state('clicked')).toBe(true);
  });
});

OuterComponent.test.js

var rawData = ["foo", "bar", "foobar", "barbaz", "boo" ]
var unwantedData = ["foo","baz"]
var cleanData = rawData.filter((item)=> !unwantedData.includes(item))
console.log(cleanData)