-
-
Save ruyaoyao/729dbae54ca698d5ed92144519311974 to your computer and use it in GitHub Desktop.
[Node.js] 如何用 mockery.js + sinon.js 來驗證
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
class DepClass { | |
constructor (arg) { | |
console.log(arg); | |
} | |
say (word) { | |
console.log(word); | |
} | |
} | |
module.exports = DepClass; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-env mocha */ | |
'use strict'; | |
// 用來 mock require 進來的 class | |
const mockery = require('mockery'); | |
// 用來監看物件行為 (不是 mock) | |
const sinon = require('sinon'); | |
// 待測試目標 | |
const TargetClass = require('./target'); | |
// 這裡不是用 require ,只是路徑字串 | |
const DepClass = './dep'; | |
// 這邊一定要用 mockery.enable 和 mockery.disable | |
before(() => mockery.enable()); | |
after(() => mockery.disable()); | |
// 用完 mock 要 deregister ,避免後面出錯 | |
afterEach(() => mockery.deregisterMock(DepClass)); | |
it('testMockeryAndSinon', function () { | |
// 真正用來取代的 mock object | |
const fakeDep = { say: () => {} }; | |
// 建立監看物件 | |
const fakeDepMock = sinon.mock(fakeDep); | |
// 建立一個假的 constructor | |
const fakeDepConstructor = sinon.spy(() => fakeDepMock.object); | |
// 會傳給 DepClass constructor 的參數 | |
const arg = 'foo'; | |
// 用假的 constructor 來取代掉實際的 DepClass | |
mockery.registerMock(DepClass, fakeDepConstructor); | |
// 預期 DepClass 的 say 方法會被呼叫 | |
fakeDepMock.expects('say').once().withExactArgs('ok'); | |
// 實際要執行的程式碼 | |
new TargetClass(arg); | |
// 預期假的 constructor 會被呼叫 | |
sinon.assert.calledWithExactly(fakeDepConstructor, arg); | |
// 驗證上面的 expects 是否有被真的呼叫 | |
fakeDepMock.verify(); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
class TargetClass { | |
constructor (arg) { | |
const DepClass = require('./dep'); | |
const dep = new DepClass(arg); | |
dep.say('ok'); | |
} | |
} | |
module.exports = TargetClass; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment