Chai 是一个流行的断言库,用于方便地测试非常复杂的 JavaScript 代码。 在本文中,我们将探讨使用 Chai 可以写出扩展而简洁的测试套件的技巧。
安装 Chai
使用 NPM 进行安装:
npm install chai --save-dev
引入 Chai
我们可以通过以下方式引入 Chai:
const chai = require('chai');或者
import { expect } from 'chai';使用 Chai 的基本语法
我们可以使用以下 Chai 断言:
expect
- expect(x).to.be.a('string');
- expect(x).to.equal(y);
- expect(x).to.be.true; // ...false
- expect(x).to.be.null; // ...undefined
- expect(fn).to.throw(Error);
assert
- assert.typeOf(x, 'string');
- assert.equal(x, y);
- assert.isTrue(x); // ...isFalse
- assert.isNull(x); // ...isUndefined
- assert.throw(fn, Error);
链式语法
Chai 也支持链式语法,这样我们可以在同一行代码中实现多个断言,而不需要为每个断言编写单独的代码行。
比如:
expect(x + y).to.be.a('number').and.to.be.at.least(5);上面的代码断言了 x + y 应该是一个数字,并且至少应该是 5。
这是一段非常简短的代码,但是它实现了多个断言并且更易读。
描述符
如果你想为断言写更长而描述性的语言,那么描述符将成为你的朋友。描述符可用于每个渐变和最终断言。
例如,假设您正在测试一个用于将 RGB 颜色转换为十六进制颜色的函数。你最终的断言可能如下所示:
expect(rgbColorToHex('100, 255, 5')).to.equal('#64ff05');上面的代码段功能健全,但是如果你与其他人分享代码,其他人可能难以理解在逻辑上发生了什么。
通过描述符的使用,我们可以将代码更清晰地表达。
expect(rgbColorToHex('100, 255, 5'))
.to.be.a.string('rgbColorToHex function converts RGB to hex')
.which.is.equal('#64ff05', 'Values match #64ff05'); 上面的代码段使用了多种描述符,使代码更易读。
Hooks
对于测试套件,很重要的一个方面是初始化和拆卸过程。 在 Chai 中,您可以使用钩子来声明开始和结束要执行的代码块。
// www.javascriptcn.com code example
describe('beforeEach and afterEach hooks examples', () => {
beforeEach(() => {
// 在运行每个测试之前,执行此代码块。
});
afterEach(() => {
// 在运行每个测试之后,执行此代码块。
});
it('should run this test', () => {
// 运行测试代码。
});
it('should run this test', () => {
// 运行测试代码。
});
it('should run this test', () => {
// 运行测试代码。
});
});使用 “beforeEach” 和 “afterEach” 钩子,可以简化重复代码。
预期语法(expect/should)
在 Chai 中,您可以选择使用 “expect” 或 “should” 语法来表达您的测试代码。
以下是使用 expect 语法的示例:
expect(x).to.be.a('string');
expect(x).to.equal(y);
expect(x).to.be.true; // ...false
expect(x).to.be.null; // ...undefined
expect(fn).to.throw(Error);以下是使用 should 语法的示例:
x.should.be.a('string');
x.should.equal(y);
x.should.be.true; // ...false
x.should.be.null; // ...undefined
fn.should.throw(Error);在应用程序中使用哪种应该是您的选择。 如果您有一个喜欢使用一种风格的团队,则最好使用此风格。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d8061ea941bf7134e505c7