首页 > 解决方案 > 为什么在茉莉花中默认将allowRespy设置为false?

问题描述

我是初学者,Jasmine我想知道为什么将默认值allowRespy设置为false

标签: jasmine

解决方案


我找到了这个答案,其中解释说jasmine.spyOn()总是返回第一个创建的间谍,所以我假设标记它的原因是为了防止使用带有状态的模拟。

我可以提出一个简化的示例,其中这种行为可能会出现问题:

describe("TestedService", () => {
   const testedService = TestBed.inject(TestedService) // configuration is ommited for simplicity

   it("calls foo only once", () => {
       const fooSpy = spyOn(testedService, 'foo')
       testedService.doAction()
       expect(fooSpy).toHaveBeenCalledOnce()

       
      fooSpy = spyOn(testedService, 'foo') // creating new spy to check if it will be called for the second time
      testedService.doAction()
      expect(fooSpy).not.toHaveBeenCalledOnce() // fails the test because it still points to the same spy,that was called few moments later. 
   })
})

另一个更现实的问题行为示例是,当您想spy通过创建一个新spy的 withspyOn函数来重置测试中使用的 a 时,但您不会被创建,而是spy使用旧状态。

例子


describe("TestedService", () => {
    beforeEach(() => {
      TestBed.inject(TestedService) // configuration is ommited for simplicity
      spyOn(TestedService, 'foo').and.returnValue(100)
    })

    .... 
    it('tests TestedService behavior when foo returns undefined', () => {
        spyOn(TestedService, 'foo') // expect it to set spy return value to undefined, 
but it don't, so the test below does not tests behavior when foo returns undefined
        .....
    }) 
}) 
 

其他示例和更正将不胜感激!


推荐阅读