2016-07-15 63 views
0

我是單元測試新手,並且已經閱讀了一些關於使用javascript的練習的教程。我會用一個愚蠢的例子來解釋我的問題。如何用mocha chai和sinon獨立測試javascript函數?

比方說,約翰需要上學,想知道他是準備去他要檢查,如果他有他的袋子,他的耳機了。這與下面的函數調用:

john.isReadyToGo; 

的isReadtToGo()函數的一個角色目標的實現如下:

characher.isReadyToGo = function() { 
    return this.hasBag() && this.hasHeadPhones(); 
} 

characher.hasBag = function() { 
    // return true or false 
} 

characher.hasHeadPhones = function() { 
    //return true or false 
} 

現在,讓我們說,我想測試此功能。在單元測試中,建議測試功能而不受其他功能的影響。這意味着在這種情況下,我將不得不測試三個函數,但character.isReadyToGo()函數需要爲this.hasBag()和this.hasHeadPhones()模擬值。我對嗎?

如果是這樣,你能不能給我我怎麼能嘲笑這兩個值的提示?

回答

1

下面是一個例子:

let character = {}; 

character.isReadyToGo = function() { 
    return this.hasBag() && this.hasHeadPhones(); 
} 

character.hasBag = function() { 
    // return true or false 
} 

character.hasHeadPhones = function() { 
    //return true or false 
} 

const sinon = require('sinon'); 
const expect = require('chai').expect; 

describe('Is character ready?',() => { 

    beforeEach(() => { 
    sinon.stub(character, 'hasBag'); 
    sinon.stub(character, 'hasHeadPhones'); 
    }); 

    afterEach(() => { 
    character.hasBag.restore(); 
    character.hasHeadPhones.restore(); 
    }); 

    it("Not if they don't have a bag or headphones",() => { 
    character.hasBag.returns(false); 
    character.hasHeadPhones.returns(false); 
    expect(character.isReadyToGo()).to.be.false; 
    }); 

    it("Not if they have headphones but no bag",() => { 
    character.hasBag.returns(false); 
    character.hasHeadPhones.returns(true); 
    expect(character.isReadyToGo()).to.be.false; 
    }); 

    it("Not if they have a bag but no headphones",() => { 
    character.hasBag.returns(true); 
    character.hasHeadPhones.returns(false); 
    expect(character.isReadyToGo()).to.be.false; 
    }); 

    it("Yes, if they have a bag and headphones",() => { 
    character.hasBag.returns(true); 
    character.hasHeadPhones.returns(true); 
    expect(character.isReadyToGo()).to.be.true; 
    }); 

}); 

對於每個測試,此短截線character.hasBagcharacter.hadHeadphones(這在beforeEach完成)。這基本上用一個你可以控制的新功能(存根)替換原來的。

根據測試,存根被「告知」每個函數返回的內容(使用.returns()),調用isReadyToGo,並根據期望檢查其結果。

每次測試後,存根被恢復(意味着原來的功能被恢復)。

+0

小細節 - 不應該是'.to.be.true();'而不是'.to.be.true;'? –

+0

@JoeWhite [no](http://chaijs.com/api/bdd/#true)= D – robertklep

相關問題