Javascript 无法比较包含绑定到React中我的类的函数的对象

Javascript 无法比较包含绑定到React中我的类的函数的对象,javascript,reactjs,ecmascript-6,jestjs,enzyme,Javascript,Reactjs,Ecmascript 6,Jestjs,Enzyme,我的类具有以下构造函数: constructor() { super(); this.togglePlay = this.togglePlay.bind(this); this.toggleMute = this.toggleMute.bind(this); this.toggleMaximize = this.toggleMaximize.bind(this); this.state = { play: false, mute

我的类具有以下构造函数:

constructor() {
    super();

    this.togglePlay = this.togglePlay.bind(this);
    this.toggleMute = this.toggleMute.bind(this);
    this.toggleMaximize = this.toggleMaximize.bind(this);

    this.state = {
      play: false,
      mute: false,
      maximize: false,
      actions: {
        togglePlay: this.togglePlay,
        toggleMute: this.toggleMute,
        toggleMaximize: this.toggleMaximize
      }
    };
  }
在我的测试中,我想比较一下

it('should have the correct state', () => {
    const wrapper = shallow(<Provider {...minProps} />);

    const expectedState = {
      play: false,
      mute: false,
      maximize: false,
      actions: {
        togglePlay: () => {},
        toggleMute: () => {},
        toggleMaximize: () => {}
      }
    };

    const actualState = wrapper.state();

    expect(expectedState).toEqual(actualState);
  });

由于功能比较,测试失败。如何通过此测试?

测试失败,因为您正在比较不同的函数引用,在模拟中您正在创建匿名函数,并且它们需要明确绑定到构造函数上。使此测试通过的一种方法是访问组件实例,然后访问绑定函数并将其分配给模拟状态:

it('should have the correct state', () => {
    const wrapper = shallow(<Provider {...minProps} />);

    const expectedState = {
      play: false,
      mute: false,
      maximize: false,
      actions: {
        togglePlay: wrapper.instance().togglePlay,
        toggleMute: wrapper.instance().toggleMute,
        toggleMaximize: wrapper.instance().toggleMaximize
      }
    };

    const actualState = wrapper.state();

    expect(expectedState).toEqual(actualState);
});

虽然不是100%确定最后一个想法,但希望它能有所帮助

您正在使用哪个断言库。@front\u end\u dev Jest(或Expect)
it('should have the correct state', () => {
    const wrapper = shallow(<Provider {...minProps} />);

    const expectedState = {
      play: false,
      mute: false,
      maximize: false,
      actions: {
        togglePlay: wrapper.instance().togglePlay,
        toggleMute: wrapper.instance().toggleMute,
        toggleMaximize: wrapper.instance().toggleMaximize
      }
    };

    const actualState = wrapper.state();

    expect(expectedState).toEqual(actualState);
});
it('should have the correct state', () => {
    const wrapper = shallow(<Provider {...minProps} />);

    const expectedState = {
      play: false,
      mute: false,
      maximize: false,
      actions: {
        togglePlay: expect.any(Function),
        toggleMute: expect.any(Function),
        toggleMaximize: expect.any(Function)
      }
    };

    const actualState = wrapper.state();

    expect(expectedState).toEqual(actualState);
});