Mocha Chai 自定义比较函数

Mocha Chai custom comparison function

我对 Mocha 和 Chai 完全陌生。我在测试中创建了一个用于比较两个对象的函数。

function compareExtremelyCompexObject (testedObject, trueObject);

如何编写使用我的 compareExtremelyCompexObject 函数断言测试的 Mocha Chai 规范?

我有这样的东西:

it('should create a specific complex object from boilerplate data', function(done) {
  importDataFromSystem().
    .end(function(err, res){
          var dummyComplexObject = getBoilerplateComplexObject();
          compareExtremelyCompexObject(res, dummyComplexObject);
          done();
      });
    });
});

到目前为止我找到的示例缺少如何比较复杂对象。用"should"/"expect"可以实现吗?

如果这还不够清楚,请告诉我。我真的已经研究这个问题好几天了。任何帮助将不胜感激!

我认为您应该稍微编辑一下您的问题,以简化,但根据我收集到的信息,您想使用您的自定义函数断言您的新对象 === 测试对象?如果是这样,并假设 compareExtremelyCompexObject returns 是对还是错,那么您就快到了。

it('should create a specific complex object from boilerplate data', function(done) {
  importDataFromSystem()
    .end(function(err, res){
          var dummyComplexObject = getBoilerplateComplexObject();
          // with assert
          assert(compareExtremelyCompexObject(res, dummyComplexObject));
          // or with chai expect
          expect(compareExtremelyCompexObject(res, dummyComplexObject)).to.be.true;
          done();
      });
    });
});

根据您的评论,您 importDataFromSystem 链接的方式暗示它 returns 一个流、承诺或它本身。假设它是一个在 'end' 上调用回调的流,那么 res 可能就是您要查找的内容,因此上面的示例应该有效。但是,如果 res 不是您要查找的内容,那么您可能必须解决承诺并链接 thenables 以确保操作的同步顺序。例如

it('should create a specific complex object from boilerplate data', function(done) {

  Promise.resolve()
    .then(function(){
         return importDataFromSystem();
    })
    .then(function(){
         return assert(compareExtremelyCompexObject(getNewlyCreatedObject(), getBoilerplateComplexObject()));
         // assert should throw error and be caught if the two objects are not equal
    })
    .then(function(){
         done()
    })
    .catch(function(err){ 
         done( err ); 
    });

});

当然,您需要一些方法来获取您创建的对象。那是完全不同的讨论。您应该编辑您的问题以将主题缩小到只处理自定义比较的断言。 (或者冒被否决的风险,我很可能会被代理人否决。=])