Luc*_*ito 9 tdd unit-testing jasmine
我正在研究使用 Jasmine JS 的 TDD 和单元测试,我对他们的方法有疑问。
我找到了两种方法,想知道有什么区别。
describe('Teste do toContain', () => {
var name = 'Lucas de Brito Silva'
it('Deve demonstrar o uso do toContain', () => {
expect(name).toContain('Lucas');
});
});
Run Code Online (Sandbox Code Playgroud)
describe('Teste do toMatch', function () {
var text = 'Lucas de Brito Silva'
it('deve validar o uso do toMatch', () => {
expect(text).toMatch('Brito');
});
})
Run Code Online (Sandbox Code Playgroud)
VLA*_*LAZ 11
不同之处部分在于他们操作的内容,还有他们将要做的事情。
以下是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");
});
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
它确实展示了他们可以做什么。
toContain将适用于数组和字符串。使用Array#includesor本质上是相同的String#includes- 将检查数组或字符串是否具有与参数匹配的项目(对于数组)或子序列(对于字符串)。expect(something).toContain(other)将大致像检查something.includes(other) === true。toMatch而是使用正则表达式。所以,首先,它只适用于字符串,而不适用于数组。其次,如果给定一个字符串作为参数,则从中生成一个正则表达式。所以,expect(something).toMatch(other)实际上会被解析为 if 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);
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
在这里,message字符串的值是foo\dbar但是如果你从中生成一个正则表达式,那么它不会匹配同一个字符串,因为\d表示一个数字 -foo4bar将匹配但不匹配foo\dbar。
| 归档时间: |
|
| 查看次数: |
5985 次 |
| 最近记录: |