【问题标题】:How to organize code for unit testing BDD using Mocha Chai?如何使用 Mocha Chai 组织单元测试 BDD 的代码?
【发布时间】:2014-08-28 19:47:36
【问题描述】:

我尝试使用 BDD 风格的 Mocha/Chai 进行单元测试。不知道从哪里开始。以下是核心代码结构。假设 getTemplates 是一个 ajax 调用,我如何处理应用程序的不同阶段。对于即在 init 函数中点击 sh.setTemplates() 之前,它经历了几个条件。如何对这些条件进行单元测试?

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


});

【问题讨论】:

  • 祝你好运,在与 BDD 相同的问题上,我一直在碰壁。如果我弄清楚了,我会回复一个答案。

标签: javascript unit-testing bdd mocha.js chai


【解决方案1】:

如何对这些条件进行单元测试?

使用以下流程:

  • 创建分支函数
  • 将断言放在分支函数中
  • 使用变体作为参数
  • 使用真实值调用一次
  • 用虚假值再次调用它

参考文献

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 2020-02-28
    • 2023-04-11
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 2015-11-18
    相关资源
    最近更新 更多