Packhouse
Search…
⌃K

Unit Test

Packhouse Test
能針對每個環節進行測試,這是函數式程式設計的優點之一,而Packhouse提供了一種簡單的Mock方法能應付所有細節:
Test是一個Plugin,使用前必須先引用:
let Test = require('packhouse/plugins/Test')
let Packhouse = require('Packhouse')
let packhouse = new Packhouse()
packhouse.plugin(Test)
let group = {
tools: {
sum: {
handler(self, v1, v2) {
self.success(v1 + v2)
}
}
}
}
packhouse.addGroup('math', () => ({ data: group }))
// mock options
packhouse.test.mock('tool', 'math/sum', options => {
options.handler = self => self.success(50)
})
packhouse.tool('math/sum').action(10, 20, (error, result) => {
console.log(result) // 50
})
// restore
packhouse.test.restore('tool', 'math/sum')
packhouse.tool('math/sum').action(10, 20, (error, result) => {
console.log(result) // 30
})

Restore All

將所有Mock物件回到原樣:
packhouse.test.restoreAll()

使用mocha與chai

mochachai分別為單元測試庫與斷言庫,這只是一個泛用測試組合,以下範例說明如何應用Packhouse進行測試:
let { expect } = require('chai')
let Test = require('packhouse/plugins/Test')
let Packhouse = require('Packhouse')
let packhouse = new Packhouse()
packhouse.plugin(Test)
let group = {
tools: {
sum: {
handler(self, v1, v2) {
self.success(v1 + v2)
}
}
}
}
describe('#Test', function() {
this.timeout(0)
before(function() {
packhouse.test.mock('tool', 'math/sum', options => {
options.handler = self => self.success(50)
})
})
after(function() {
packhouse.test.restore('tool', 'math/sum')
})
it('test', function(done) {
packhouse.tool('math/sum').action(10, 10, (error, result) => {
expect(result).to.equal(50)
})
})
})