gpt4 book ai didi

javascript - 无法比较包含绑定(bind)到我的 React 类的函数的对象

转载 作者:行者123 更新时间:2023-11-30 14:18:15 25 4
gpt4 key购买 nike

我的类有以下构造函数:

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);
});

运行测试时,我收到以下错误:

Expected value to equal:
{"actions": {"toggleMaximize": [Function bound toggleMaximize], "toggleMute": [Function bound toggleMute], "togglePlay": [Function bound togglePlay]}, "maximize": false, "mute": false, "play": false}
Received:
{"actions": {"toggleMaximize": [Function toggleMaximize], "toggleMute": [Function toggleMute], "togglePlay": [Function togglePlay]}, "maximize": false, "mute": false, "play": false}

由于功能比较,测试失败。我怎样才能通过这个测试?

最佳答案

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

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);
});

通过这种方式,您指向相同的绑定(bind)函数及其引用。

另一种可行的解决方案是使用 jest's expect.any(constructor)

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);
});

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

关于javascript - 无法比较包含绑定(bind)到我的 React 类的函数的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53183124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com