What are Mocha equal tests?

前端 未结 2 827
心在旅途
心在旅途 2021-01-13 13:40

I am testing an Express Node app with Mocha. I would like to have the following test (comparing two empty arrays):

assert.equal [], []

to p

相关标签:
2条回答
  • 2021-01-13 14:29

    The problem is that an array is a reference type in JavaScript, and hence only the reference is compared. And, of course, if you create two different empty arrays independent of each other, they are two different objects and have two different references.

    That's why the test fails.

    You basically have the same issues with objects (no deep-equal is done), although you often are not interested in whether two objects are identical, but whether their contents are the same.

    That's why I wrote a module to handle this: comparejs. This module - besides some other nice things - solves this issue by offering comparison by value and comparison by identity, for all (!) types. I guess that's what you need here.

    As you are especially asking for the context of mocha, I have also written my own assert-module, called node-assertthat, which internally makes use of comparejs. As a side effect, you get a more readable (as more fluent) syntax. Instead of

    assert.equal(foo, bar);
    

    you can write

    assert.that(foo, is.equalTo(bar));
    

    Perhaps this may be the way for you to go.

    PS: I know that self-advertisement is not wanted on Stackoverflow, but in this case the tools I've written for myself simply solve the original poster's question. Hence please do not mark this answer as spam.

    0 讨论(0)
  • 2021-01-13 14:33

    If you're comparing objects ({} or []) you have to use assert.deepEqual() because if you do assert.equal([], []) you're just comparing the references: {} === {} (or [] === []) will be always false.

    http://nodejs.org/api/assert.html#assert_assert_deepequal_actual_expected_message

    0 讨论(0)
提交回复
热议问题