代码之家  ›  专栏  ›  技术社区  ›  Armeen Moon

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

  •  1
  • Armeen Moon  · 技术社区  · 6 年前

    背景:

    我的测试框架是笑话和酶。我有一个叫做 Lazyload 与一个 LazyloadProvider React.ContextAPI . 我想写一个测试来保证 componentDidMount 懒汉 构件内支撑法 this.props.lazyload.add() hasBeenCalledWith(this.lazyRef) 是有效的

    我开玩笑说我能监视懒鬼的 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?
      });
    })
    
    1 回复  |  直到 6 年前
        1
  •  6
  •   Alejandro    6 年前

    你可以通过 stubbed add lazyload toHaveBeenCalledWith 匹配器,如果它接受 instance() 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); 
      });
    })