次のコードでは、名前チェックを行うテストを調整してもよいかどうか疑問に思っていました。ID を null にできないことを確認するコードを追加すると、最初の 3 つのテストが失敗するためです。
同じことが、id テストを行う最後の 3 つのテストにも当てはまります。名前の原因として「foo」を使用する必要があります。そうしないと、これらのテストも失敗します。それも大丈夫かどうかわかりませんか?
テストするコード:
class Error
class Node
constructor: (name, id) ->
if not name?
throw new Error('Name cannot be null')
@name = name
if not id?
throw new Error('Id cannot be null')
@id = id
window.Node = Node
仕様:
node_spec = describe 'Node', () ->
it 'should have the name foo', () ->
expect( new Node('foo').name ).toEqual('foo')
it 'should have the name bar', () ->
expect( new Node('bar').name ).toEqual('bar')
it 'should throw an error if the name is null', () ->
expect( () -> new Node() ).toThrow()
it 'should have an id of 0', () ->
expect( new Node('foo', 0).id ).toEqual(0)
it 'should have an of 1', () ->
expect( new Node('foo', 1).id ).toEqual(1)
it 'should throw an error if id is null', () ->
expect( new Node('foo') ).toThrow()
window.node_spec = node_spec
更新: 解決策の 1 つは、id と name の両方にゲッター メソッドとセッター メソッドを用意し、代わりにそれらをテストすることだと思います。