Angular的Jasmine测试用例2-导航到其他页面

dev*_*iwa 6 javascript jasmine karma-jasmine angular

我正在使用jasmine编写角度2代码的测试用例.我试图在用户注销后导航回登录页面.如何测试页面位置?

Pau*_*tha 5

您真正需要做的就是测试是否使用正确的参数(即登录页面的路由)调用了路由器导航方法。尝试测试实际导航可能会导致比单元测试所需的更多副作用。

要检查该Router.navigate方法是否被调用,只需使用存根并监视它。

@Component({})
class SomeComponent {
  constructor(private router: Router) {}

  logout() {
    this.router.navigate(['/login'])
  }
}

let routerStub;

beforeEach(() => {
  routerStub = {
    navigate: jasmine.createSpy('navigate');
  }
  TestBed.configureTestModule({
    declaration: [ SomeComponent ],
    providers: [
      { provide: Router, useValue: routerStub }
    ]
  });
});

it('it should navigate to login after user logs out', () => {
  let component = TestBed.createComponent(SomeComponent).componentInstance;
  component.logout();

  expect(routerStub.navigate).toHaveBeenCalledWith(['/login']);
})
Run Code Online (Sandbox Code Playgroud)


Nat*_*May -1

Angular 团队努力将测试纳入 Angular 环境的所有本机方面。如果您使用本机角度路由器,那么他们已经构建了测试供您使用。查看此博客。如果您不使用角度路由器,那么我认为您只能靠自己了。