如何使用业力茉莉花测试进行页面导航(路由)

问题描述 投票:0回答:1

我正在编写有角度的(Karma-Jasmine)测试用例,我想在页面之间导航。如何使用业力茉莉花在页面之间导航。

karma-jasmine
1个回答
0
投票

1)测试使用导航的组件:执行操作时应调用navigation方法(断言如toHaveBeenCalled或toHaveBeenCalledWith)

it('should redirect the user to the users page after saving', () => {
  let router = TestBed.get(Router);
  let spy = spyOn(router, 'navigate');

  component.save();

  expect(spy).toHaveBeenCalledWith(['users'])
});

2)还测试您的路由将使用适当的组件

app.routes.spec.ts
import { routes } from './app.routes'

it('should contain a route for users', () => {
  expect(routes).toContain({path: 'users', component: UserComponent})
});

3)您可以使用useValue来测试不同的ActivateRouteParams(只需进行配置然后传递给提供者,请参见示例)。组件ts文件示例:

ngOnInit() {
  this.contextType = this.route.snapshot.paramMap.get('contextType');
  this.contextId = this.route.snapshot.paramMap.get('contextId');
  this.contextFriendlyId = this.route.snapshot.paramMap.get('contextFriendlyId');
}

规范文件(configureTestData是允许您传递不同的可配置值的函数,在我的情况下为ActivateRouteParams)

export function configureTestData(activatedRouteParams) {
  beforeEach(async(() => {
     TestBed.configureTestingModule({
        declarations: [SetUpComponent],
        imports: [RouterTestingModule],
        providers: [
           {
              provide: ActivatedRoute, useValue: activatedRouteParams
           }
        ]
     });
  }));
}


describe('SetUp Component:Folder ', () => {
  let component: SetUpComponent;
  let fixture: ComponentFixture<SetUpComponent>;


  configureTestData({
     snapshot: {
        paramMap: convertToParamMap({
           contextType: 'Folder',
           contextId: 'FX6C3F2EDE-DB25-BC3D-0F16-D984753C9D2E',
           contextFriendlyId: 'FX17373'
        })
     }
  });

  beforeEach(() => {
     fixture = TestBed.createComponent(SetUpComponent);
     component = fixture.componentInstance;
     fixture.detectChanges();
  });

  it('should create set up component for folder', () => {
     expect(component).toBeTruthy();
  });

  it('should create alert with required properties', () => {
     expect(component.contextType).toEqual('Folder);

   .... etc
  });
});

4)路由器出口和routerLink模板文件:

<nav>
  <a routerLink="todos"></a>
</nav>
<router-outlet></router-outlet> 
beforeEach(() => {
  TestBed.configureTestingModule({
     imports: [RouterTestingModule.withRoutes([])],
     declarations: [AppComponent]
  });
});

it('should have router outlet', () => {
  let de = fixture.debugElement.query(By.directive(RouterOutlet));

  expect(de).not.toBeNull();
});

it('should have a link to todos page', () => {
  let debugElements = fixture.debugElement.queryAll(By.directive(RouterLinkWithHref));

  let index = debugElements.findIndex(de => de.properties['href'] === '/todos');
  expect(index).toBeGreaterThan(-1);
});
© www.soinside.com 2019 - 2024. All rights reserved.