参考にさせて頂いたページ
以前書いた記事
mochaとchaiを使うことについて以前書いた記事です。
この続きという感じでsinon.jsのstubを使っていきます。
前提としてこちらを読んでおくと解りやすいかもしれません。
jQueryとsinonをインストールする
npm install --save-dev jquery sinon
package.jsonのdevDependenciesは以下の4つになりました。
"devDependencies": { "chai": "^4.0.1", "jquery": "^3.2.1", "mocha": "^3.4.2", "sinon": "^4.1.2" }
例えばapplication.jsにmyObjを追記する
application.jsに以下のようなmyObjを書いたことを想定してテストケースも書いていきます。
jQueryの$.ajax()でhttps://example.com/hoge
のAPIにリクエストを送信するオブジェクトです。
window.myObj = { request: function() { return $.ajax({ url: 'https://example.com/hoge', type: 'GET', dataType : 'text', }); }, successFn: function(response){ console.log(response); }, };
js_testing/spec/example_com_hoge_api.spec.jsの作成とその記述内容
describe()とit()はmochaの関数で、chai.assert.strictEqual()はchaiのメソッドです。
sinonをインストールしたのでstub()が使用できます。
describe('example.com/hoge apiへのリクエスト', function() { it('apiが文字列"hoge"を返す', function() { var stub = sinon.stub(window.myObj, 'request'); stub.returns({ done: function(callback) { callback('hoge'); } }); window.myObj.request().done(function(data) { chai.assert.strictEqual('hoge', data); stub.restore(); }); }); });
js_testing/js_testing_0001.htmlに追記する
以下の三行を追記しました。
<script src="node_modules/jquery/dist/jquery.js"></script>
<script src="node_modules/sinon/pkg/sinon.js"></script>
<script src="spec/example_com_hoge_api.spec.js"></script>
以下の通りになりました。
<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="utf-8"> <title></title> <meta name="description" content=""> <meta name="author" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--mochaによるテストの実行結果用cssを読み込み--> <link rel="stylesheet" href="node_modules/mocha/mocha.css"> <link rel="shortcut icon" href=""> </head> <body> <!--mochaによるテストの実行結果が出力されるdiv--> <div id="mocha"> </div> <!--jquery, mocha, chai, sinon を読み込み--> <script src="node_modules/jquery/dist/jquery.js"></script> <script src="node_modules/chai/chai.js"></script> <script src="node_modules/mocha/mocha.js"></script> <script src="node_modules/sinon/pkg/sinon.js"></script> <script> //BDDスタイルを使用するので設定 mocha.setup('bdd'); </script> <!--自分が作っているwebアプリケーションのjsを読み込み--> <script src="js/application.js"></script> <!--テストコードを読み込み--> <script src="spec/add_numbers.spec.js"></script> <script src="spec/example_com_hoge_api.spec.js"></script> <script> // テストを実行 mocha.run(); </script> </body> </html>
js_testing/js_testing_0001.htmlをブラウザで開いてテストを実行してみる
js_testing/js_testing_0001.htmlをChromeなどのブラウザで開いてテストを実行してみます。
テストはグリーンでした。
sinon.fakeServer.create()
を使う方法も参考にさせて頂いたページに書いてありました。
書いてみたものの
これだと実際に使っているAPIやメソッドに対するテストケースではなくて、sinon.jsで代替APIを作ってテストしているに過ぎないので、非同期処理がからむ一連の挙動についてはspyでsetUpをしたらできるのか、実際のAPIにselenium等でリクエストして返却される結果を検証する方が良いのかもうちょっと調査と理解が必要そう。
spyのsetUpとかjQueryのajaxメソッドをテストする例については Spies - Sinon.JS を参照するのがよさそうです。
jasmine2とかtestdouble.jsとかではどうなんでしょうね。