【问题标题】:how to mock an event trigger within a jasmine test如何在茉莉花测试中模拟事件触发器
【发布时间】:2022-11-02 05:30:25
【问题描述】:

我的组件代码有:

function aa() {
this.component.grid = createItem();
this.component.grid.instance.options.addEventListener('eventAbc',() => { 
  this.bbb ();
})
}

function bbb() {
 console.log("dummy func");
}

在 component.spec.ts 文件中:

let content;
setup() {

content = jasmine.createSpyObj('content', ['createItem']);
content.createItem.and.callFake(() => {
return { 
grid: {
 instance: {
  options: {
      addEventListener: (event, action) => {}
  }}}}}

it('testing method aa', () => { 
spyOn(component.grid.instance.gridOptions, 'addEventListener').andCallThrough();
spyOn(component, 'bbb').and.callThrough();
component.aa();
expect(component.grid.instance.gridOptions.addEventListener).toHaveBeenCalled();
expect(component.bbb).toHaveBeenCalled();
}

我想了解如何模拟触发“abcEvent”,以便测试进入事件侦听器的真实回调并调用 bbb 方法。

【问题讨论】:

    标签: angular jasmine karma-jasmine


    【解决方案1】:

    我会在回调中调用action,以便调用bbb 方法。

    像这样的东西:

    content.createItem.and.callFake(() => {
    return { 
    grid: {
     instance: {
      options: {
          addEventListener: (event, action) => {
           // !! add the following line, call action method so when you pass
           // bbb there it will be called
           action();
        }
      }}}}}
    

    【讨论】:

      【解决方案2】:

      我访问事件侦听器的回调函数的方式是:

      let callBack = addEventListener.calls.allArgs()[0][1]; //this gives access to all the arguments passed to the eventListener method
      callBack(); //manually triggered the callback function bbb()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-25
        • 1970-01-01
        • 2018-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多