角单元测试“如果不采取零件”

时间:2019-11-27 14:17:47

标签: angular unit-testing karma-jasmine

 Dname = JSON.stringify(this.userDetails);
  Dpass = JSON.stringify({
    userName: 'test',
    password: 'test'
  });

  onSubmit() {
    this.userDetails = this.inputForm.value;
    this.submitted = true;
    if (this.Dname === this.Dpass) {
      this.router.navigate(['/page1']);
      console.log('ok');
    } else {
      console.log('not ok');
    }
  }

If path not taken --can someone help me to solve this issue in angular unit testing

2 个答案:

答案 0 :(得分:0)

您可以窥探navigate的{​​{1}}功能并使用toHaveBeenCalledWith

答案 1 :(得分:0)

您应该在beforeEach testBed.configureTestingModule中将它们设置为相等:

.then(() => {
     fixture = TestBed.createComponent(YourComponent);
     component = fixture.componentInstance;
     component.Dname = component.Dpass
});

这些值的计算结果为true,您可以通过将spyOn用作此方法,并使用.callThrough命中该路径。这是一个示例:

it('should execute methodName', () => {
        const spy = spyOn(component, 'methodName').and.callThrough();
        component.methodName();
        expect(spy).toHaveBeenCalled();
 });