【发布时间】:2011-03-06 11:48:14
【问题描述】:
在下面的代码中,我想知道是否可以调整进行名称检查的测试。因为一旦我添加了检查 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 方法,然后测试它们。
【问题讨论】:
-
您忘记提及您使用的是哪个测试库。看起来像Speks?
-
更多 StackOverflow 问题?
-
是的,我也是这么想的。我是否删除此问题并将其复制粘贴到 SO?
-
不,不要复制粘贴。点击“举报”并请版主为您移动。
-
一个建议:假设您希望拒绝非字符串名称,您可能希望将
name?检查替换为typeof name is 'string'。同样,也许typeof id is 'number'而不是number?。或者,如果您想允许非字符串名称或非数字 id,您应该在某些测试用例中使用它们。