82 lines
2.8 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
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
2022-02-04 17:28:24 +01:00
[source,javascript]
----
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.
});
});
----
== Resources
* 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)
=== Message
Primary: Change this assertion to not compare dissimilar types ("XXX" and "YYY").
Secondary: Last assignment of "ZZZ".
=== Highlighting
Primary: the called assertion function with its arguments.
Secondaries (if args are variables): the last assignment of the variable.
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]