【问题标题】:Jest/Jasmine .toContain() fails even though matching values are present即使存在匹配值,Jest/Jasmine .toContain() 也会失败
【发布时间】:2017-06-14 11:18:49
【问题描述】:

我正在编写一个带有 Button 组件的简单 React 应用程序,如下所示:

import React, { Component } from 'react';
// shim to find stuff
Array.prototype.contains = function (needle) {
  for (var i = 0; i < this.length; i++) {
       if (this[i] == needle) return true;
   }
   return false;
};

class Button extends Component {
  propTypes: {
    text: React.PropTypes.string.isRequired,
    modifiers: React.PropTypes.array
  }
  render() {
    return(
      <span className={this.displayModifiers()}>{this.props.text}</span>
    );
  }
  displayModifiers() {
    const modifiers = this.props.modifiers || ["default"];
    if (modifiers.contains("default") ||
      modifiers.contains("danger")  ||
      modifiers.contains("success")) {
      // do nothing
    } else {
      // add default
      modifiers.push("defualt");
    }
    var classNames = "btn"
    for (var i = 0; i < modifiers.length; i++) {
      classNames += " btn-" + modifiers[i]
    }
    return(classNames);
  }
}

export default Button;

然后我写了这个来测试它:

it("contains the correct bootstrap classes", () => {
  expect(mount(<Button modifiers={["flat"]}/>).html()).toContain("<span class=\"btn btn-flat btn-default\"></span>");
});

该代码应该可以通过,但我收到以下错误消息:

expect(string).toContain(value)

Expected string:
  "<span class=\"btn btn-flat btn-defualt\"></span>"
To contain value:
  "<span class=\"btn btn-flat btn-default\"></span>"

  at Object.it (src\__tests__\Button.test.js:42:293)

任何想法为什么这没有通过?

【问题讨论】:

    标签: node.js reactjs jasmine jestjs


    【解决方案1】:

    来自文档:

    当您想要检查项目是否在列表中时,请使用 .toContain

    要测试字符串,您应该使用toBetoEqual

    it("contains the correct bootstrap classes", () => {
      expect(mount(<Button modifiers={["flat"]}/>).html()).toBe("<span class=\"btn btn-flat btn-default\"></span>");
    });
    

    但是有更好的方法来测试输出渲染的组件:snapshots

    it("contains the correct bootstrap classes", () => {
      expect(mount(<Button modifiers={["flat"]}/>).html()).toMatchSnapshot();
    });
    

    请注意,您需要enzymeToJson 才能使用酶进行快照测试。

    【讨论】:

    • 谢谢。我用.toEqual 替换了.toContain,但它仍然说字符串不匹配。快照测试有效,但我不喜欢使用它。任何想法为什么.toEqual 在字符串相同时不起作用?
    • 因为defualt中有错字;)
    • 好收获!我想我看这个有点太久了:)
    • 只是和工具对比了一下,也看不出来。
    • 文档还说:.toContain can also check whether a string is a substring of another string.
    猜你喜欢
    • 2021-08-11
    • 1970-01-01
    • 2015-06-25
    • 2014-12-03
    • 1970-01-01
    • 2017-07-15
    • 2020-11-16
    • 2013-09-26
    相关资源
    最近更新 更多