iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 22
0
Modern Web

從零開始認識 Node.js系列 第 22

[Day 22] 動手篇 - Please give me Mocha (2)

TDD

Koa 測試何如寫?

接續上一篇 [Day 21] 動手篇 - Please give me Mocha (1) ,基本需要的 Package 都安裝好。

  • 設定測試時需要的 Server

    • 沒設定測試時會執行預設的 Server
    • test/config 新增 app.js ,檔案內容如下:
    const koa = require('koa');
    const app = koa();
    
    // 模擬 Client request 的發送
    global.request = require('supertest').agent(app.listen());
    
    const router = require('koa-router');
    
    // Mocha 語法,在執行測試 "前" 做的準備動作
    before((done) => {
        // 這個判斷不是必要,這裡是為了確定測試時的狀態設定在 test
        if (app.env !== 'test') {
            let errorInfo = new Error('NODE_ENV isn\'t test.');
            return done(errorInfo);
        }
    
        router.get('/', function *() {
            this.body = 'Hello World!';
        });
        app.use(router());
    
        app.listen(3000, function () {
            console.log('Example app listening on port 3000!');
            return done();
        });
    });
    
  • 第一個測試

    • test/controller 新增 first.spec.js ,檔案內容如下:
    describe('Controller and service\' s testing.', () => {
    
        it('This is a Controller.', (done) => {
    
            request.get('/').end((err, res) => {
                if (err) return done(err); // 與 Server 相關錯誤
                if (res.statusCode !== 200) return done(res); // 與 API 有關的錯誤
    
                // 這裡取 response 的 text 而非 body 的原因是我前面給 body 是文字,非物件,因此這裡取 response 的 body 會得到 undefined
                const result = res.text;
    
                // 透過 shuldjs 來比對預期的結果
                result.should.equal('Hello World!');
    
                return done();
            })
        });
    });
    
  • 執行測試

    • Mocha 安裝在全域
      env NODE_ENV=test mocha
    • Mocha 安裝在 package.json
      env NODE_ENV=test ./node_modules/mocha/bin/mocha
  • 測試結果

    • 成功
      http://ithelp.ithome.com.tw/upload/images/20161221/20102342w96InIs2Ow.png
    • 失敗
      http://ithelp.ithome.com.tw/upload/images/20161221/201023425XkKkD07Ek.png

上一篇
[Day 21] 動手篇 - Please give me Mocha (1)
下一篇
[Day 23] 動手篇 - 等等!什麼是 Webhooks?
系列文
從零開始認識 Node.js31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言