简体   繁体   English

如何使用Mocha Chai组织单元测试BDD的代码?

[英]How to organize code for unit testing BDD using Mocha Chai?

I trying unit testing using Mocha/Chai using BDD style. 我尝试使用BDD风格使用Mocha / Chai进行单元测试。 Not sure where to start. 不知道从哪里开始。 Following is what the core code structure is. 以下是核心代码结构。 Assuming that getTemplates is an ajax call, how do I the different stages of an application. 假设getTemplates是一个ajax调用,我该如何处理应用程序的不同阶段。 For ie before hitting sh.setTemplates() in init function, it has go through few conditions. 对于ie在init函数中遇到sh.setTemplates()之前,它已经经历了几个条件。 How to unit test those conditions? 如何对这些条件进行单元测试?

// Javascript     
function myFunc(id){
var mf = this;
mf.id = id;
mf.init = function(){return init()};
mf.isIdValid = function(){return isIdValid()};
mf.setTemplates = function(){return setTemplates};
mf.getTemplates = function(){return getTemplates};

// Init
mf.init();


///////////////////////
function init(){

    if(!id){
        return false;
    }


    if(!sh.isIdValid()){
        return false;
    }

    sh.setTemplates();
}


///////////////////////
function setTemplates(){
    getTemplates(function(callBackTemplate){
        if(!callbackTemplate){
            return false;
        }

        // inject to dom
    });
}

///////////////////////
// Async call
function getTemplates(){

    return '<div>Test</div>';
}
}



///////////////////////////////////////
/////////////////////////////////////////
TEST JS Mocha/Chai

var expect = chai.expect;

describe('myFunc Class', function(){
var mf;

before(function(){
    mf = new myFunc(1);
});


describe('mf.init()', function(){

    it('should not result false', function(){
        var result = mf.init();
        expect(result).to.not.equal(false);
    });


});

How to unit test those conditions? 如何对这些条件进行单元测试?

Use the following process: 使用以下过程:

  • Create a branch function 创建分支函数
  • Put the assertion in the branch function 将断言放在分支函数中
  • Use the variant as an argument 使用variant作为参数
  • Call it once with a truthy value 用truthy值调用一次
  • Call it again with a falsy value 用假值再次调用它

References 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM