【问题标题】:jest: test case for returning null. I tried diff solutions but not works for me笑话:返回 null 的测试用例。我尝试了差异解决方案,但不适用于我
【发布时间】:2019-12-04 13:49:04
【问题描述】:

我要测试return null;

我已经尝试过 expect(comp.type()).toEqual(null)expect(comp.get(0)).toBeFalsy() 都不适合我。

abc.js

render() {
    const { hasError } = this.state;
        if (hasError) {
            return null;
        }
    .....
}

abc.test.js

it('+++ incorporates Search', () => {
        wrapper.setState({ hasError: true });
        console.log(wrapper.debug());
});

控制台为我提供数据。

【问题讨论】:

  • 这不起作用。我没有让包装器为空。我正在使用数据包装

标签: javascript jestjs


【解决方案1】:

这取决于您使用的渲染库。如果是酶,您可以:

expect(wrapper.getElement()).toBe(null);

感谢https://github.com/airbnb/enzyme/issues/52

如果你使用其他库应该有类似的东西。但你知道吗?我相信你最好不要做这么严格的检查。返回空字符串而不是 null 在浏览器中应该看起来相同。因此,进行如此狭窄的测试时,您会在自己的腿上开枪。

只检查wrapper.text() 是否为空应该是不错的选择。

PS 还考虑用一些基于props 的(传递prop、更改prop、通过simulate 调用prop 等)通信替换wrapper.setState。因为您的代码可能无法在componentDidUpdate 中设置this.state.hasError,但您永远不会知道这一点,因为您的测试直接设置了state

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 2023-02-22
    • 1970-01-01
    相关资源
    最近更新 更多