Chai アサーションの数
ChaiJS 用プラグインで、テストごとに実行されたアサーションや expected の数をチェックできます。
このチェックが必要な理由
テストを見てみましょう。
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
の内部で切り替えて、もう 1 つの 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
は、実行されたアサーションの数を計算します。このメソッドと前のメソッドの主な違いは、1 つの expect
で複数のアサーションが行われる可能性があることです。次の例でこれを説明します。
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);
});
});
2 つ の expected がありますが、2 つとも実行されます。同時に、「内部」には3 つ のアサーションがあります。最初の expect
には 1 つのアサーションがあります。ただし、2 番目の expect
には 2 つのアサーションがあります。1 つはプロパティ length
が存在するかチェックし、もう 1 つは値をチェックします。そのため、expectAssertions
カウンターにご注意ください。
メソッド expectExpects
はほとんどのケースをカバーできるため、expectAssertions
は 99.9% 使用されません。
制限事項
- Expect スタイルでのみ機能します。
expectExpects
またはexpectAssertions
が失敗すると、現在のテストスイートの他のテストを停止します。