2017-07-07 866 views
7

我想測試,如果在我的測試中調用了特定的函數並且參數正確。從JEST文檔我無法弄清楚,什麼是正確的方法來做到這一點。如何使用已定義的參數(toHaveBeenCalledWith)測試函數是否被調用

比方說,我有這樣的事情:

在單元測試
// add.js 

function child(ch) { 
    const t = ch + 1; 
    // no return value here. Function has some other "side effect" 
} 


function main(a) { 
    if (a == 2) { 
    child(a + 2); 
    } 

    return a + 1; 
} 

exports.main = main; 
exports.child = child; 

現在:

1. 我想運行main(1)並測試它的返回2child()不叫。

2. 然後我想運行main(2),並返回3child(4)只被調用一次。

我現在是這樣的:

// add-spec.js 
module = require('./add'); 

describe('main',() => { 

    it('should add one and not call child Fn',() => { 
    expect(module.main(1)).toBe(2); 
    // TODO: child() was not called 
    }); 

    it('should add one andcall child Fn',() => { 

    expect(module.main(2)).toBe(3); 
    // TODO: child() was called with param 4 exactly once 
    // expect(module.child).toHaveBeenCalledWith(4); 
    }); 

}); 

我在https://repl.it/languages/jest測試這一點,所以在這個REPL工作示例將非常感激。

回答

7

好吧,我已經想通了。訣竅是將功能拆分成單獨的文件。因此,代碼是(在https://repl.it/languages/jest作品):

// add.js 
child = require('./child').child; 

function main(a) { 
    if (a == 2) { 
    child(a + 2); 
    } 

    return a + 1; 
} 

exports.main = main; 

提取child.js文件:

// child.js 

function child(ch) { 
    const t = ch + 1; 
    // no return value here. Function has some other "side effect" 
} 

exports.child = child; 

主要測試文件:

// add-spec.js 
main = require('./add').main; 
child = require('./child').child; 

child = jest.fn(); 

describe('main',() => { 

    it('should add one and not call child Fn',() => { 
    expect(main(1)).toBe(2); 

    expect(child).toHaveBeenCalledTimes(0); 
    }); 

    it('should add one andcall child Fn',() => { 
    expect(main(2)).toBe(3); 

    expect(child).toHaveBeenCalledWith(4); 
    expect(child).toHaveBeenCalledTimes(1); 
    }); 

}); 
相關問題