在下面的代码中,我想知道是否可以调整进行名称检查的测试。因为一旦我添加了检查 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 方法,然后对其进行测试。
最佳答案
根据下面的 matyr 评论进行编辑:我最初认为这是由于 new
的怪异造成的。运算符,因为一些测试使用语法 new Foo().bar
。然而,new
在这种情况下,行为正如皮克斯所预期的那样。因此,尽管这个答案不是上述问题的解决方案,但为了后代,这里有一个评论:
当你写的时候
new A().B
您引用的是 B
新的属性A
实例。
但是如果你写
new A.B()
(或者只是 new A.B
—CoffeeScript 会在 new
目标的末尾隐式添加括号,如果它们不存在的话)那么您将创建 A.B
的新实例。这变得非常令人困惑——什么是 new A().B()
?—因为new
运算符有其自己特殊的优先级规则。因此,我建议使用括号来阐明此类代码,例如
(new A).B
new (A.B)
有discussion here关于试图在 CoffeeScript 中使这种行为更加直观,但经过一番努力,确定“治疗方法比疾病更糟糕。”
关于javascript - 测试: Parameter input validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5207054/