0

我正在为以下代码块编写测试用例:

someFn() {
    if (this.loginStatus === '1') {
      this.router.navigate(['/login']);
    } 
}

在我的规范文件中:

import { Router } from '@angular/router'
describe('MyComponent', () => {
 let routerStub;
 beforeEach(async(() => { 
   routerStub = {
      navigate: jasmine.createSpy('navigate'),
    };
   TestBed.configureTestingModule({
     declarations: [MyComponent],
     providers: [       
        { provide: Router, useValue: routerStub },
      ],
   }).compileComponents()
 });

 beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.autoDetectChanges();
  });

  it('navigate to login', () => {
     component.loginStatus = '1';
     component.someFn();
     expect(routerStub.navigate).toHaveBeenCalledWith(['/login']);
  });
})

上面给了我错误: Expected spy navigate to have been called with [ [ '/login' ] ] 但它从未被调用过。

我该如何解决这个问题?我已经尝试了很多来自 SO 的解决方案,但似乎没有什么对我有用。

代码是用 Angular 7 编写的,我使用的是 jasmine+karma。

4

1 回答 1

0

尝试以下方式:

import { Router } from '@angular/router'
    describe('MyComponent', () => {
     let router: Router;
     beforeEach(async(() => { 
       TestBed.configureTestingModule({
         declarations: [MyComponent],
         providers: [       
            { provide: Router, useValue: routerStub },
          ],
       }).compileComponents()
     });

     beforeEach(() => {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
        router = TestBed.get(Router);
        fixture.detectChanges();
      });

      it('navigate to login', () => {
      const spy = spyOn(router, 'navigate');
         component.loginStatus = '1';
         component.someFn();
         expect(router.navigate).toHaveBeenCalledWith(['/login']);
      });
    })

使用 routerStub 的另一种方法:-

       import { Router } from '@angular/router';
 
       class RouterStub {
          public navigate(params: any[]): void {}
        }
 
        describe('MyComponent', () => {
         let router: Router;
         beforeEach(async(() => { 
           TestBed.configureTestingModule({
             declarations: [MyComponent],
             providers: [       
                { provide: Router, useClass: RouterStub },
              ],
           }).compileComponents()
         });
        
         beforeEach(() => {
            fixture = TestBed.createComponent(MyComponent);
            component = fixture.componentInstance;
            router = TestBed.get(Router);
            fixture.detectChanges();
          });
        
          it('navigate to login', () => {
          const spy = spyOn(router, 'navigate');
             component.loginStatus = '1';
             component.someFn();
             expect(router.navigate).toHaveBeenCalledWith(['/login']);
          });
        })
于 2020-05-06T19:19:13.120 回答