音の鳴るブログ

鳴らないこともある

何もしないメソッドのテスト

たとえばこういう感じのクラスがあって

class Hoge
  nop: ->
  evil_nop: ->
    # do "rm -rf /"
    undefined

describe 'Hoge', ->
  it '#nop should do nothing', ->
    instance = new Hoge()
    test = instance.nop()
    expect(test).to.be.undefined

nop のテストを

  • 何もしない

と、した場合。

上のように書いてしまうとテストしにくい。(実装が evil_nop でもテストは通ってしまう)

なので

// nop.js
module.exports = function() {};
nop = require './nop'

# chai をちょっと拡張して
chai.use (chai, utils)->
  utils.addProperty chai.Assertion.prototype, 'nop', ->
    @assert(
      utils.flag(@, 'object') is nop,
      'expected #{this} to be nop',
      'expected #{this} to be not nop',
      !@negate
    ) 
nop = require './nop'

class Hoge
  nop: nop

describe 'Hoge', ->
  it '#nop should do nothing', ->
    instance = new Hoge()
    expect(instance.nop).to.be.nop

みたいにしている。

nop 自体のテストはしなくても良さそうだけど、どうしてもしたかったらこんな感じだと思う。

nop = require './nop'

describe 'nop', ->
  it 'should do nothing', ->
    str = nop.toString().replace /\s/g, ''
    expect(str).to.equal 'function(){}'
    expect(-> do nop).to.not.throw()