茉莉花的间谍在图像加载事件中不起作用



我正在使用karma jasmine和browserfy来测试Vue组件。一种方法是在图像加载事件上侦听。但是调用事件处理程序的间谍没有得到正确的结果。以下片段显示了错误:

let spy = jasmine.createSpy('spy')
spy.and.returnValues({
  name: 'name'
})
describe('example tests', () => {
  it('should pass', (done) => {
    var img = new Image()
    img.onload = function() {
      console.log('2', spy())
      done()
    }
    img.src = "http://dummyimage.com/100x100"
    console.log('1', spy())
  })
})

这里,在位置1,日志显示1,但在位置2,日志显示未定义。

链接到spy的.and.returnValues函数将只返回一次指定的对象,所有后续对spy的调用都将返回undefined。

如果您要执行以下操作:

let spy = jasmine.createSpy('spy')
spy.and.returnValues({
  name: 'name'},
 {name: 'name2'}
)
describe('example tests', () => {
  it('should pass', (done) => {
    var img = new Image()
    img.onload = function() {
    console.log('2', spy())
    done()
    }
    img.src = "http://dummyimage.com/100x100"
    console.log('1', spy())
  })
})

您会发现控制台将记录"1对象{名称:"名称"}",然后记录2对象{姓名:"名称2"}。

如果你想让间谍总是返回相同的对象,你需要使用.and.returnValue而不是.and.returnValues:

let spy = jasmine.createSpy('spy')
spy.and.returnValue({
  name: 'name'})
describe('example tests', () => {
  it('should pass', (done) => {
    var img = new Image()
    img.onload = function() {
    console.log('2', spy())
    done()
    }
    img.src = "http://dummyimage.com/100x100"
    console.log('1', spy())
  })
})

最新更新