在下面的代码中,我想知道是否可以调整进行名称检查的测试。因为一旦我添加了检查 ID 不能为空的代码,我的前 3 个测试就会失败。
最后 3 个进行 id 测试的测试也是如此。我必须使用“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
更新: 我想一种解决方案是为 id 和 name 设置一个 getter 和 setter 方法,然后测试它们。