【问题标题】:Unit Test case to Mock object to function单元测试用例模拟对象功能
【发布时间】:2020-03-12 13:12:34
【问题描述】:

如何传递事件模拟对象并获得验证

onCallFunction() {
      const eventValue = event;
            if (!eventValue.relatedTarget || !eventValue.relatedTarget.last.contain('value')) {
                super.onCallFunction();
            }
     }

在 Testbed 中声明事件 const 但无法理解如何传递给函数以执行代码

describe('relatedTarget test', () => {
  compoenent = fixture.componentInstance;

  it('should have value for property newValue', () {
    spyOn('component', 'onCallFunction');
    const event = {event: 
    { 
    relatedTarget: 
    {
     last: { 
      contain: (param) => {} 
     } 
    }
    }};
    component.onCallFunction();
    expect(component.onCallFunction).toHaveBeenCalled();
  })

});

【问题讨论】:

    标签: javascript angular jasmine


    【解决方案1】:

    首先,您没有正确拼写“组件”,因此将声明更改为:

    component = fixture.componentInstance;
    

    您还应该像这样将该行包装在 beforeEach 中:

    beforeEach(() => {
      component = fixture.componentInstance;
    });
    

    然后改变你的间谍,让它实际上是对函数的间谍,并将其声明为变量:

    const spy = spyOn<any>(component, 'onCallFunction');
    

    并更改期望以实际询问间谍是否已被调用:

    expect(spy).toHaveBeenCalled();
    

    现在,当您调用 component.onCallFunction() 并期望它已被调用时,测试应该会通过,但我无法理解“事件”变量的含义是什么?你到底想在这里测试什么?

    【讨论】:

    • event 是 const 属性,我试图在下面为这个对象设置值:eventValue.relatedTarget || !eventValue.relatedTarget.last.contain('value') 当前解决方案只是验证方法是否被调用,但负面情况我必须通过将值设置为 eventValue 进行测试
    • 是的,好的。那么从哪里来的财产呢?你的组件编译了吗?现在看来,const eventValue = event 不仅是多余的,而且是未定义的。
    • 事件是我尝试做的例子,有没有办法在函数eventValue.relatedTarget || !eventValue.relatedTarget.last.contain('value') 中设置这一行的值
    • onCallFunction 可以接受一个输入值,所以:onCallFunction(eventValue) {...}
    • 但是onCallFunction中没有参数onCallFunction(),请看组件部分
    猜你喜欢
    • 1970-01-01
    • 2023-03-09
    • 2021-10-13
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多