# Unit Test

能針對每個環節進行測試，這是函數式程式設計的優點之一，而Packhouse提供了一種簡單的Mock方法能應付所有細節：

{% hint style="info" %}
Test是一個[Plugin](/the-instance/plugin.md)，使用前必須先引用：
{% endhint %}

```javascript
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物件回到原樣：

```javascript
packhouse.test.restoreAll()
```

## 使用mocha與chai

[mocha](https://mochajs.org/)與[chai](https://www.chaijs.com/)分別為單元測試庫與斷言庫，這只是一個泛用測試組合，以下範例說明如何應用Packhouse進行測試：

```javascript
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)
        })
    })
})
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://packhouse-doc.metalsheep.com/tooling/unit-test.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
