摩卡茶自定义比对功能

人气:173 发布:2022-10-16 标签: javascript node.js chai integration-testing mocha.js

问题描述

我对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();
      });
    });
});

到目前为止,我找到的示例缺少如何比较复杂对象。可以用"应该"/"期望"来实现吗?

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

推荐答案

我认为您应该稍微编辑一下您的问题,以简化问题,但从我收集的信息来看,您想用您的自定义函数来断言您的新对象=测试对象?如果是这样,并且假设compareExtremelyCompexObject返回TRUE或FALSE,那么您就快成功了。

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链接的方式意味着它返回一个流、承诺或本身。假设它是一个在‘end’上调用回调的流,那么res可能就是您要寻找的,所以上面的例子应该可以工作。然而,如果res不是您要寻找的,那么您可能必须解析承诺并链接使能以确保操作的同步顺序。

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 ); 
    });

});

但当然,您需要某种方法来获取您创建的对象。这完全是另一回事。您应该编辑您的问题,将主题范围缩小到只处理自定义比较的断言。(或者冒着被否决的风险,我将被代理人否决。=])

446