首页 > 解决方案 > 如何使用 Jest 将 prop 中的 spyOn 方法传递给组件?

问题描述

背景:

我的测试框架是 Jest 和 Enzyme。我有一个名为的组件Lazyload,它与LazyloadProviderusing耦合React.ContextAPI。我想编写一个测试来保证 组件内部 prop 方法componentDidMount的on已被调用。使用 Jest spy 我希望这是有效的Lazyloadthis.props.lazyload.add()hasBeenCalledWith(this.lazyRef)

我开玩笑说能够窥探 Lazyload 的register方法;但是,我无法弄清楚如何监视内部道具方法this.props.lazyload.add

问题:

我如何写一个笑话间谍this.props.lazyload.add并确保它被调用this.lazyRef

class Lazyload extends Component<LazyloadProps, LazyloadState> {
  lazyRef: ReactRef;

  constructor(props) {
    super(props);
    this.lazyRef = createRef();
  }

  componentDidMount() {
   this.register()
  }

  register() { // not spy on this.
    this.props.lazyload.add(this.lazyRef); // spyOn this
  }
}

测试:

describe('lazyload', () => {
  let provider;
  beforeEach(() => {
    provider = shallow(
      <LazyloadProvider>
        <p>Wow</p>
      </LazyloadProvider>
    ).instance();
  });

  it('should register a lazyloader with add', () => {
    const spy = jest.spyOn(Lazyload.prototype, 'register');

    const wrapper = shallow(
      <Lazyload lazyload={provider.engine}>
        <p>doge</p>
      </Lazyload>
    ).instance();

    expect(spy).toHaveBeenCalled(); // this works however it's a better test to spy on the this.prop.lazyload.add method.. but how?
  });
})

标签: javascriptreactjsjestjsenzymespy

解决方案


您可以在道具中传递存根 ,并检查toHaveBeenCalledWith匹配器是否接受instance()的:addlazyloadlazyref

describe('lazyload', () => {

  it('should add ref', () => {
    const lazyloadStub = {
        add: jest.fn();
    };

    const wrapper = shallow(
      <Lazyload lazyload={lazyloadStub}>
        <p>doge</p>
      </Lazyload>
    );

    expect(lazyloadStub.add).toHaveBeenCalledWith(wrapper.instance().lazyRef); 
  });
})

推荐阅读