如何使用Jest将prop内部的spyOn方法传递给组件?

Mat*_*ood 6 javascript spy reactjs jestjs enzyme

背景:

我的测试框架是Jest和Enzyme。我有一个Component Lazyload,它耦合到LazyloadProviderusing React.ContextAPI。我想编写一个测试,关于担保 componentDidMount的的Lazyload组件内道具的方法this.props.lazyload.add()被调用。我希望使用Jest间谍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
  }
}
Run Code Online (Sandbox Code Playgroud)

测试:

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?
  });
})
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 6

你可以通过存根 addlazyload道具,并与检查toHaveBeenCalledWith匹配,如果它接受实例()lazyref

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); 
  });
})
Run Code Online (Sandbox Code Playgroud)