single mock of object in nested describe functions (jasmine
如果我有一个带有嵌套的describe方法的jasmine规格,并且想对某个方法进行监视,让它返回特定的结果,那么在所有方法中,正确的方法是什么?我知道我可以在顶级方法中简单地定义间谍,但是,这是否意味着我的某些测试得到了相同的对象?我不希望将一项测试中的更改保留在另一项测试中,即使它允许代码重用。
所以,如果我有这样的事情:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | describe ('tope level test', function(){ var FOO; beforeEach( module ('FooBar') ); beforeEach( inject (function( _Foo_){ FOO=_Foo_; FOO.bar=jasmine.createSpy('foobar').andReturn("baz"); })); describe('test A', function(){ if('sub1', function(){ FOO.newMethod=function() {'this shouldn't exist'}; }); if('sub2', function(){ FOO.newMethod(); }); })]); |
我认为sub2能够访问newMethod,因为sub1定义了它,并且定义FOO的beforeEach运行在开始任务A处,但仅运行FOO,因此sub1和sub2共享相同的FOO。正确吗?
假设是正确的,我如何才能在最高级别的description中添加一个间谍,同时又确保每次在测试中使用该对象时都会重新生成该对象,而每次都只包含所需的间谍?
使用Object.create()创建对象的新实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | describe ('tope level test', function(){ var FOO; beforeEach( module ('FooBar') ); beforeEach( inject (function( _Foo_){ FOO = Object.create(_Foo_); FOO.bar = jasmine.createSpy('foobar').andReturn("baz"); }); describe('test A', function(){ if('sub1', function(){ FOO.newMethod = function() {'this shouldn\'t exist'}; expect(FOO.bar).toBeDefined(); expect(FOO.newMethod).toBeDefined(); }); if('sub2', function(){ expect(FOO.bar).toBeDefined(); expect(FOO.newMethod).not.toBeDefined(); }); }); |