非同期通信のテスト書くのに時間がかかりました.
環境はUbuntu12.04の64bit版です.
まずは環境を整えます.
CoffeeScriptとVows,それらをインストールするのに必要なものをインストールします.
% sudo apt-get install nodejs curl g++ % curl -k https://npmjs.org/install.sh | sudo sh % sudo npm install -g coffee-script vows
このコマンドを実行したディレクトリにnode_modulesというディレクトリができます.
僕はホームディレクトリで行なっています.
このコマンドで今回のテストを走らせるのに必要なライブラリが揃います.
% sudo npm install jQuery vows jsdom xmlhttprequest
今回はGitHubを検索し,その検索結果をHTMLに追加するというプログラムをテストすることにします.
sampleGh.coffee
class SampleGh
searchUrl = 'https://api.github.com/legacy/repos/search/'
search: (keyword, callback) =>
$.ajax {
url : searchUrl + keyword
dataType : 'jsonp'
success : (data, status) => callback(data)
}
exports?.SampleGh = SampleGh
view.coffee
class View
constructor: (@el = document) ->
renderRepositories: (repositories) =>
reception = $('#repositories', @el)
for repository in repositories
reception.append "<li>#{repository.name} @#{repository.owner}"
exports?.View = View
これがテストのソースコードです. test-samplegh.coffee
vows = require 'vows'
assert = require 'assert'
global.$ = require 'jQuery'
SampleGh = require('./samplegh').SampleGh
View = require('./view').View
getBaseHtml = => $ '<div><ul id="repositories"></ul></div>'
vows.describe('SampleGh').addBatch
'検索前':
topic: => $ '#repositories', getBaseHtml()
'まだリポジトリの数は0です': (repositories) =>
assert.equal 0, repositories.children().size()
'検索後':
topic: =>
promise = new (require('events')).EventEmitter
new SampleGh().search 'coffeescript', (data) =>
html = getBaseHtml()
new View(html).renderRepositories data.data.repositories
promise.emit('success', $('#repositories', html))
promise
'取得してHTMLに追加されています': (repositories) =>
assert.isNotZero repositories.children().size()
.export module
このコマンドでテストを走らせることができます.
% vows test-samplegh.coffee --spec実行結果
% vows test-samplegh.coffee --spec
♢ SampleGh
検索前
✓ まだリポジトリの数は0です
検索後
✓ 取得してHTMLに追加されています
✓ OK » 2 honored (2.493s)
このテストは実際にGitHubのAPIを叩いているので,何度も実行しているとAPI使用制限に達してテストが走らなくなってしまいます.
0 件のコメント:
コメントを投稿