jasmine - 为什么在茉莉花中默认将allowRespy设置为false?
问题描述
我是初学者,Jasmine
我想知道为什么将默认值allowRespy
设置为false
?
解决方案
我找到了这个答案,其中解释说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
.....
})
})
其他示例和更正将不胜感激!
推荐阅读
- rpc - 什么取代了 pmap_set 命令?
- c# - 使用 htmlagilitypack 选择特定的 td
- laravel - Laravel 错误:调用字符串上的成员函数 format()
- elasticsearch - 判断elasticsearch恢复失败
- ms-access - MS Access 组合框显示选项卡
- html - SVG 光标有不需要的灰色边缘
- android - 将 ImageButton 放在两个视图组之间
- amazon-web-services - 权限有助于设置用户对 S3 的访问权限
- javascript - IIFE:如果我返回警报而不将其包装在函数中,为什么我的代码会忽略 addEventListener?
- keras - 使用 Keras 添加和访问辅助 tf.Dataset 属性