Chai 斷言計數
ChaiJS 外掛,可檢查每個測試執行了多少斷言或期望。
為什麼需要檢查它?
讓我們看看這個測試
import InstanceGenerator from '../lib/instances-generator';
describe('suite #1', () => {
it('test #1', () => {
class S1T1A {
/* Other props and methods are skipped */
/**
* I'm called after any instance of S1T1A is created
*/
afterCreate(...args) {
// I need to check `args` here
// chai.expect(args)...
}
}
InstanceGenerator.create(S1T1A, 3); // create 3 instances of S1T1A
});
});
這個測試看起來很簡單,但主要問題是,如果不使用虛擬標記,就無法判斷 afterCreate
是否被呼叫。必須在測試的最上方初始化它。然後必須在 afterCreate
內切換它,並且在測試結束時必須加入另一個 expect
。
測試變得較難閱讀。
更好的方法是檢查執行了多少個 expect
。
安裝
npm i -D chai-assertions-count
或
yarn add -D chai-assertions-count
外掛
像使用其他 Chai 外掛一樣使用此外掛。
const chai = require('chai');
const chaiAssertionsCount = require('chai-assertions-count');
chai.use(chaiAssertionsCount);
用法
const chai = require('chai');
const chaiAssertionsCount = require('chai-assertions-count');
chai.use(chaiAssertionsCount);
describe('suite #2', () => {
beforeEach(() => {
chai.Assertion.resetAssertsCheck();
});
afterEach(() => {
// you don't need both of them
chai.Assertion.checkAssertionsCount();
chai.Assertion.checkExpectsCount();
});
});
方法 resetAssertsCheck
只是刪除內部計數器,且必須在每個測試之前使用。
方法 checkExpectsCount
計算 chai.expect
被呼叫的次數。如果您的測試使用 Expect 風格,請使用此方法。
方法 checkAssertionsCount
計算執行了多少個斷言。此方法與前一個方法的主要區別在於,單個 expect
可能執行多個 assertion
。下面的範例說明了這一點
const chai = require('chai');
const chaiAssertionsCount = require('chai-assertions-count');
chai.use(chaiAssertionsCount);
describe('suite #3', () => {
it('test #1', () => {
chai.Assertion.expectAssertions(3);
chai.Assertion.expectExpects(2);
chai.expect(1).to.be.equal(1);
chai.expect([]).to.have.property('length', 0);
});
});
這裡有兩個 expect,我們「期望」它們都會被執行。同時,在「幕後」有三個斷言。第一個 expect
有一個單一斷言。但是,第二個 expect
有兩個斷言。第一個檢查是否存在 length
屬性,另一個檢查其值。因此,請注意 expectAssertions
計數器。
方法 expectExpects
可以涵蓋大多數情況,因此 expectAssertions
在 99.9% 的情況下不會使用。
限制
- 僅適用於 Expect 風格。
- 在
expectExpects
或expectAssertions
失敗時,停止目前套件中的其他測試。