【问题标题】:Why does deepEqual fail for my array of strings coming from a mongoose doc?为什么 deepEqual 对来自猫鼬文档的字符串数组失败?
【发布时间】:2014-10-07 04:46:08
【问题描述】:

我在 equal 和 deepEqual 上看到了一些有用的帖子,但我仍然不明白为什么这个 mocha 测试失败了。

describe('remove(thing)', function(){
    it('should remove the word from the wordlist if it is there', function(){
        var wordlist1 = new Wordlist('unit1');
        wordlist1.add("bird");
        wordlist1.add("elephant");
        wordlist1.add("cat");
        wordlist1.add("dog");
        assert.equal(wordlist1.find("bird"), 0);      //passes
        wordlist1.remove('bird');
        assert.equal(wordlist1.words[0], "elephant"); //passes
        assert.equal(wordlist1.words[1], "cat");      //passes
        assert.equal(wordlist1.words[2], "dog");      //passes
        var thingie = ["elephant", "cat", "dog"];
        assert.deepEqual(wordlist1.words, thingie);   //fails
    })
});

我尝试过使用单引号而不是双引号并更改括号周围的间距,但它们都告诉我同样的事情:

AssertionError: ["elephant","cat","dog"] deepEqual ["elephant","cat","dog"] <Click to see difference>

当我点击查看差异时,WebStorm 告诉我这两件事是相同的。如果两个数组具有相同的内容,尽管我使用 deepEqual,为什么这个测试会失败?如果是因为它们是字符串,那么可以使用什么方法来检查字符串数组的相等性?

【问题讨论】:

  • 请发布您的WordList 实施
  • 可能的重复是帮助我理解尝试 deepEqual 的原因,但他们的代码适用于该断言,而我的则不行。我发现这令人困惑,这就是我首先发布问题的原因。为什么他们的 deepEqual 示例有效,而我的无效?我不明白为什么我的失败了。
  • 我的整个项目都位于github这里:github.com/kklamberty/SightWords
  • 你会尝试将wordlist1.words.toObject() 传递给断言吗? Mongoose 可能正在摆弄你的数组。

标签: javascript arrays mongoose mocha.js


【解决方案1】:

您需要在将wordlist1.words.toObject() 传递给断言之前调用它。

Mongoose 在其文档中添加了多个元数据,即使它们只是一个子文档甚至是单个属性。为确保您有一个普通的对象或数组,您始终可以在您的文档或其任何(或其属性)属性上调用 toObject。

获取裸对象的另一种方法是使用lean() 修饰符运行查询,例如Wordlist.findById(id).lean().exec()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多