LoginSignup
4
3

More than 5 years have passed since last update.

JavaScript のテストでお手軽 fixture

Posted at

Node.js ではなくブラウザでのテストの話です。

DOM が絡んだテストをするには、何らかの HTML(fixture)が必要ですが、テスト毎に HTML ファイルを用意するのは面倒です。テストコード中で簡単に fixture を用意できると便利。

Mocha には fixture の機能がありませんが、簡単に自前で用意できます。

spec_helper.js.coffee
window.useFixture = (html) ->
  stripped = html.replace(/^\s+|\s+$/g, '')
  fixture = null
  beforeEach ->
    fixture = $(stripped).appendTo('body')
  afterEach ->
    fixture.remove()

という感じで関数を用意しておくと、以下のように使えます。

something_spec.coffee
describe 'Something', ->
  describe '#doSomething', ->
    useFixture """
      <div class="view">
        <div class="something" data-something="123">Something</div>
      </div>
    """
    it 'gets data from element', ->
      something = new Something el: '.view'
      expect(something.data).to.eq 123

CoffeeScript は複数行文字列が簡単に使えていいですね。

ちなみに fixture をインラインで書いた方がいいと思うのは、fixture を外部ファイルにしていろんなテストで共有すると、テストコードを見てもテスト対象がどういう挙動をするのかわかりにくくなるためです。この辺の話はこの記事 に詳しいです。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3