Assertions are statements that check whether certain conditions are true. They are used to validate that the actual results of a code snippet match the expected outcomes. By using assertions, developers can ensure that their code behaves as intended and identify potential bugs or issues early in the development process.
An incomplete assertion refers to a situation where an assertion is written but lacks some necessary components or conditions, making it insufficient to fully validate the expected behavior of the code being tested. Writing incomplete assertions can lead to false positives or false negatives in your test suite, making it less reliable.
This rule checks for incomplete assertions with Chai.js in the following cases:
assert.fail, expect.fail or should.fail are present but not called. expect(...) or should assertion is not followed by an assertion method, such as equal. expect or should assertion ends with a chainable getters, such as .that, or a modifier, such as
.deep. expect or should assertion function, such as .throw, is not called. In such cases, what is intended to be an assertion doesn’t actually assert anything.
const assert = require('chai').assert;
const expect = require('chai').expect;
describe("incomplete assertions", function() {
const value = 42;
it("uses chai 'assert'", function() {
assert.fail; // Noncompliant: Missing the call to 'fail'
});
it("uses chai 'expect'", function() {
expect(1 == 1); // Noncompliant: Should chain with 'to.equal'
expect(value.toString).to.throw; // Noncompliant: Missing the type of the exception
});
});
Make sure to write complete and precise assertions. Always include the necessary comparison methods (e.g., .to.equal(),
.to.be.true, etc.) to make the expectations clear and leave no room for ambiguity.
const assert = require('chai').assert;
const expect = require('chai').expect;
describe("complete assertions", function() {
const value = 42;
it("uses chai 'assert'", function() {
assert.fail();
});
it("uses chai 'expect'", function() {
expect(1).to.equal(1);
expect(value.toString).to.throw(TypeError);
});
});
expect and should