首页 > 解决方案 > Jasmine - 何时使用 toContain() 或 toMatch()?

问题描述

我正在研究使用 Jasmine JS 进行 TDD 和单元测试,我对他们的方法有疑问。

我找到了两种方法,想知道有什么区别。

describe('Teste do toContain', () => {
    var name = 'Lucas de Brito Silva'
    it('Deve demonstrar o uso do toContain', () => {
        expect(name).toContain('Lucas');
    });
});
describe('Teste do toMatch', function () {
    var text = 'Lucas de Brito Silva'
    it('deve validar o uso do toMatch', () => {
        expect(text).toMatch('Brito');
    });
})

标签: unit-testingjasminetdd

解决方案


不同之处部分在于他们操作的内容,还有他们将做什么。

这是Jasmine 版本 2的示例用法(但它使用最新版本运行示例):

it("The 'toMatch' matcher is for regular expressions", function() {
  var message = "foo bar baz";

  expect(message).toMatch(/bar/);
  expect(message).toMatch("bar");
  expect(message).not.toMatch(/quux/);
});

describe("The 'toContain' matcher", function() {
  it("works for finding an item in an Array", function() {
    var a = ["foo", "bar", "baz"];

    expect(a).toContain("bar");
    expect(a).not.toContain("quux");
  });

  it("also works for finding a substring", function() {
    var a = "foo bar baz";

    expect(a).toContain("bar");
    expect(a).not.toContain("quux");
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.4.0/jasmine.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.4.0/jasmine.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.4.0/jasmine-html.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.4.0/boot.min.js"></script>

它确实证明了他们可以做什么。

  • toContain将适用于数组和字符串。Array#includes使用or本质上是相同的- 如果数组或字符串具有与参数匹配的(对于数组)或子序列(对于字符串),String#includes则将检查它。将大致像检查。expect(something).toContain(other)something.includes(other) === true
  • toMatch而是使用正则表达式。所以,首先,它只适用于字符串,而不适用于数组。其次,如果给定一个字符串作为参数,则从中生成一个正则表达式。所以,expect(something).toMatch(other)实际上会像解决一样new RegExp(other).test(something)。这确实意味着如果你想将它用于简单的字符串匹配,你应该小心不要使用特殊字符:

it("The 'toMatch' matcher generates a regex from the input", function() {
  var message = "foo\\dbar";

  expect(message).toMatch(message);
});

it("The generated matcher will obey regex restrictions", function() {
  var pattern = "foo\\dbar";

  expect(pattern).not.toMatch(pattern);
  expect("foo4bar").toMatch(pattern);
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.4.0/jasmine.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.4.0/jasmine.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.4.0/jasmine-html.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.4.0/boot.min.js"></script>

在这里,message字符串的值是foo\dbar但是如果你从中生成一个正则表达式,那么它不会匹配相同的字符串,因为\d表示一个数字 -foo4bar将匹配但不匹配foo\dbar


推荐阅读