繁体   English   中英

单元测试用例到模拟对象的功能

[英]Unit Test case to Mock object to function

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

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

在测试床中声明事件 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();
  })

});

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

component = fixture.componentInstance;

您还应该将该行包装在 beforeEach 中,如下所示:

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

然后更改您的 spy 以便它实际上是对函数的 spy 并将其声明为变量:

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

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

expect(spy).toHaveBeenCalled();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM