【问题标题】:Comparing Objects with Dates from MongoDb in Mocha在 Mocha 中将对象与来自 MongoDb 的日期进行比较
【发布时间】:2019-02-11 09:39:32
【问题描述】:

我目前在 mocha 测试中遇到问题。我想测试从 mongodb 数据库返回对象的 getById 方法。一切正常,除了日期的比较。我就是这样做的。

describe('Service.Step.getById', function(){

before(done => {
    mongoose.connect(getConnectionString());
    mongoose.connection.on('error', () => {
        console.error("Connecting to database failed");
    });
    mongoose.connection.once('open', () => {
        console.log('Connected to Database');
        done();
    });
});

it('should return a step', async function(){
    assert.equal((await StepService.getById("someId")).toObject(), {
        Title : "SomeTitle",
        _id: mongodb.ObjectID("someId"),
        SchemaVersion : "0.0.1",
        Description: "SomeDescription",
        Video: "Video.mp4",
        Image : null,
        __v : 0,
        Created : "2018-09-05T15:24:11.779Z",
        Updated :  "2018-09-05T15:24:11.779Z"
    });
});

现在的问题是,显然 mongoose 返回一个 Date 对象而不仅仅是一个字符串。 (这是测试显示的)

  • “更新”:[日期:2018-09-05T15:24:11.779Z]
  • “更新”:“2018-09-05T15:24:11.779Z”

但是,如果我将断言中的 Created(或 Updated)替换为

Created : new Date("2018-09-05T15:24:11.779Z")

我的测试完全失败了。你知道我该如何解决这个问题吗?

【问题讨论】:

    标签: node.js testing mongoose mocha.js chai


    【解决方案1】:

    equal 断言实际和预期的非严格相等 (==)。 例如

    {a:1} == {a:1} //false
    

    deepEqual 断言 actual 深度等于 expected

    assert.deepEqual({ tea: 'green' }, { tea: 'green' }); //true
    

    【讨论】:

      【解决方案2】:

      好的。答案很简单。似乎 Date 会使对象嵌套和

      assert.equal
      

      将不再适用于此。而是使用

      assert.deepEqual
      

      它会按预期工作。正确的代码是

      before(done => {
          mongoose.connect(getConnectionString());
          mongoose.connection.on('error', () => {
              console.error("Connecting to database failed");
          });
          mongoose.connection.once('open', () => {
              console.log('Connected to Database');
              done();
          });
      });
      
      it('should return a step', async function(){
          assert.deepEqual((await StepService.getById("someId")).toObject(), {
              Title : "SomeTitle",
              _id: mongodb.ObjectID("someId"),
              SchemaVersion : "0.0.1",
              Description: "SomeDescription",
              Video: "Video.mp4",
              Image : null,
              __v : 0,
              Created : new Date("2018-09-05T15:24:11.779Z"),
              Updated : new Date("2018-09-05T15:24:11.779Z")
          });
      });
      

      【讨论】:

        猜你喜欢
        • 2014-02-12
        • 1970-01-01
        • 1970-01-01
        • 2017-07-02
        • 1970-01-01
        • 1970-01-01
        • 2013-10-02
        • 1970-01-01
        • 2017-10-01
        相关资源
        最近更新 更多