68 lines
2.5 KiB
Plaintext
Raw Normal View History

Comparing two values of different types with operator ``++===++`` or ``++!==++`` will always return respectively ``++true++`` and ``++false++``. The same is true for operators ``++==++`` and ``++!=++`` when two ``++objects++`` of unrelated types, i.e. one is not a prototype of the other, are compared.
2021-02-02 15:02:10 +01:00
Chai provides assertion functions which use these operators to compare two values. These assertions should not compare values of incompatible types as they would always fail or always succeed.
== Noncompliant Code Example
----
const assert = require('chai').assert;
const expect = require('chai').expect;
const should = require('chai').should();
describe("invalid comparisons", function() {
it("uses chai 'assert'", function() {
const str = "1";
const today = new Date();
const nb = new Number(42);
// These assertions use non-strict equality. Only unrelated "object" types are considered.
assert.equal(today, nb); // Noncompliant. This always fails.
assert.notEqual(today, nb); // Noncompliant. This always succeeds.
// These assertions use strict equality. Unrelated "object" types and primitive types are considered.
assert.strictEqual(str, 1); // Noncompliant. This always fails.
assert.notStrictEqual(str, 1); // Noncompliant. This always succeeds.
// Comparing primitive types to objects with == or != is ok
// even if it is not recommended. Using strict equality is better.
assert.equal(str, [1]); // Ok
assert.notEqual(str, [0]); // Ok
});
it("uses chai 'expect' and 'should'", function() {
const str = "1";
// These assertions use strict equality
expect(str).to.equal(1); // Noncompliant. This always fails.
expect(str).to.not.equal(1); // Noncompliant. This always succeeds.
str.should.equal(1); // Noncompliant. This always fails.
str.should.not.equal(1); // Noncompliant. This always succeeds.
});
});
----
== See
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality[MDN webdoc - Equality]
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality[MDN webdoc - Strict Equality]
* S2159 Silly equality checks should not be made
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]