简体   繁体   English

如何在 Angular 中测试简单导航 function

[英]how to test simple navigate function in Angular

this is my function这是我的 function

  public onBackButtonClick(): void {
    void this.router.navigate(['/users/manage-user']);
  }

This is the test code i have written这是我写的测试代码

   const router = {
     navigate: jasmine.createSpy('navigate'),
   };
  it('should navigate to "users/manage-user" page', () => {
    component.onBackButtonClick(); // call router.navigate
    expect(router.navigate).toHaveBeenCalledWith(['/users/manage-user']);
  });

the error I am getting is我得到的错误是

   Expected spy navigate to have been called with:
   [ [ '/users/manage-user' ] ]
   but it was never called.
   Error: Expected spy navigate to have been called with:
   [ [ '/users/manage-user' ] ]
   but it was never called.

I think the problem is due to the fact that the "Route" is not enough to spy on我认为问题在于“路线”不足以监视

const routerSpy = jasmine.createSpyObj('Router', {
  navigate: of({}),
  params: of({id: 1})
});
/// in testBed
TestBed.configureTestingModule({
   providers: [{
     provide: Router,
     useValue: routerSpy,
   }],
});

you probably need to add the variable as a provider as in the example and use the CreateSpyObj method您可能需要像示例中一样将变量添加为提供程序并使用 CreateSpyObj 方法

jasmine.createSpy can be used when there is no function to spy on. jasmine.createSpy可以在没有 function 可监视时使用。 It will track calls and arguments like a spyOn but there is no implementation.它将像 spyOn 一样跟踪呼叫和 arguments,但没有实现。

jasmine.createSpyObj is used to create a mock that will spy on one or more methods. jasmine.createSpyObj用于创建将监视一个或多个方法的模拟。 It returns an object that has a property for each string that is a spy.它返回一个 object,其中每个字符串都有一个属性,它是一个间谍。

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

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