2017-07-07 4 views
7

テストで、特定の関数が正しいパラメータで呼び出された場合、テストします。 JESTのドキュメントから、私はそれを行う正しい方法は何かを理解することができません。ユニットテストで今すぐ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)を実行し、それが2を返し、child()が呼び出されなかったことをテストします。

2. そして、私はmain(2)を実行し、それは3を返し、child(4)はちょうど1回だけ呼び出されました。

私は今、このようなものを持っている:

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

}); 

私はこのREPLでの実施例は、あまり理解されるであろう、https://repl.it/languages/jestでこれをテストしています。

答えて

7

OK、わかりました。そのトリックは、関数を別々のファイルに分割することです。そうコードは(と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); 
    }); 

}); 
関連する問題