no-comparison-or-assignment-inside-ok.rst (2153B)
1 no-comparison-or-assignment-inside-ok 2 ===================================== 3 4 This rule prevents two misuses of the ``ok()`` test framework function. 5 6 Assignments 7 ----------- 8 9 The first is one where people accidentally put assignments into ``ok``, like so: 10 11 .. code-block:: js 12 13 ok(foo = bar, "Foo should be equal to bar"); 14 15 This is similar to the builtin eslint rule `no-cond-assign`_. 16 17 There is no autofix as the linter cannot tell if the assignment was intentional 18 and should be moved out of the ``ok()`` call, or if it was intended to be some 19 kind of binary comparison expression (and if so, with what operator). 20 21 .. _no-cond-assign: https://eslint.org/docs/latest/rules/no-cond-assign 22 23 Comparisons 24 ----------- 25 26 The second is a stylistic/legibility/debuggability preference, where the linter 27 encourages use of the dedicated ``Assert`` framework comparison functions. For 28 more details on ``Assert``, see :ref:`assert-module`. 29 30 This rule is autofixed, and will correct incorrect examples such as the 31 following: 32 33 Examples of incorrect code for this rule: 34 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 35 36 .. code-block:: js 37 38 ok(foo == bar); 39 ok(foo < bar); 40 ok(foo !== bar); 41 42 to something like: 43 44 Examples of correct code for this rule: 45 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 46 47 .. code-block:: js 48 49 Assert.equal(foo, bar); 50 Assert.less(foo, bar); 51 Assert.notStrictEqual(foo, bar); 52 53 54 Rationale 55 ^^^^^^^^^ 56 57 There are a few reasons the more verbose form is preferable: 58 59 - On failure, the framework will log both values rather than just one, making 60 it much easier to debug failing tests without having to manually add 61 logging, push to try, and then potentially retrigger to reproduce intermittents 62 etc. 63 - The :ref:`assert-module` is standardized and more widely understood than the old 64 mocha/mochikit forms. 65 - It is harder to make typos like the assignment case above, and accidentally 66 end up with tests that assert non-sensical things. 67 - Subjectively, when an additional message is long enough to cause ``prettier`` 68 to split the statement across multiple lines, this makes it easier to 69 see what the two operands of the comparison are.