简体   繁体   English

间歇性错误无法匹配任何路线单元测试Angular

[英]Intermittent error cannot match any routes unit testing Angular

I've read many posts on the subject about using the router testing module and trying to spy on the router.navigate method but none have resolved the issue I have. 我已经阅读了许多有关使用路由器测试模块并尝试监视router.navigate方法的文章,但没有一个解决我遇到的问题。 Every 2nd run of my tests or so I will see the error, here's the first line in full 我的测试每进行2次,我都会看到错误,这是完整的第一行

Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'post/view'

To reiterate the error has not been seen when I run my app only when testing 要重申该错误,只有在测试时才运行我的应用程序

It only appears once no matter how many tests are in the component and it's always the first test that it happens for, if I switch the order then it's the new first test that fails with this error 无论组件中有多少测试,它只会出现一次,并且始终是它发生的第一个测试,如果我切换顺序,则是新的第一个测试失败,并出现此错误

My component is as follows ( unrelated code removed for brevity ) 我的组件如下(为简洁起见,删除了不相关的代码)

export class CreatePostComponent implements OnInit {

  constructor(private postService: PostService,
              private router: Router,
              private location: Location) {
  }

  submitPost() {
    this.validMessage = '';
    if (!this.createPostForm.valid) {
      this.validMessage = 'Please fill out the form before submitting!';
      return;
    }
    const post = this.createPostForm.value as IPost;
    this.postService.createPost(post)
      .pipe(first())
      .subscribe(
        data => {
          this.createPostForm.reset();

          //Here's the call that I believe causes the issues
          this.router.navigate(['post/view']);
        },
        error => {
          return throwError(error);
        }
      );
  }
}

Here's the spec, again unrelated tests removed 这是规格,再次删除了不相关的测试

describe('CreatePostComponent', () => {
  let component: CreatePostComponent;
  let fixture: ComponentFixture<CreatePostComponent>;
  let http: HttpTestingController;
  let mockPostService;
  let mockLocationService;


  beforeEach(async(() => {
    mockPostService = jasmine.createSpyObj(['createPost']);
    mockLocationService = jasmine.createSpyObj(['back']);
    TestBed.configureTestingModule({
      declarations: [CreatePostComponent],
      imports: [ReactiveFormsModule,
        HttpClientTestingModule,
        RouterTestingModule],
      providers: [
        {provide: PostService, useValue: mockPostService},
        {provide: Location, useValue: mockLocationService}]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    http = TestBed.get(HttpTestingController);
    fixture = TestBed.createComponent(CreatePostComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

I have also tried spying on the router as below (rest of code unchanged) 我还尝试了如下监视路由器(其余代码不变)

  beforeEach(async(() => {
    mockPostService = jasmine.createSpyObj(['createPost']);
    mockLocationService = jasmine.createSpyObj(['back']);
    TestBed.configureTestingModule({
      declarations: [CreatePostComponent],
      imports: [ReactiveFormsModule,
        HttpClientTestingModule,
        RouterTestingModule],
      providers: [
        {provide: PostService, useValue: mockPostService},
        {provide: Location, useValue: mockLocationService}]
    })
      .compileComponents();

    spyOn<any>(component['router'], 'navigate').and.returnValue(true);
  }));

and I have tried injecting my own mock for navigate as below 我尝试注入我自己的模拟物进行导航,如下所示

  beforeEach(async(() => {
    mockPostService = jasmine.createSpyObj(['createPost']);
    mockLocationService = jasmine.createSpyObj(['back']);
    TestBed.configureTestingModule({
      declarations: [CreatePostComponent],
      imports: [ReactiveFormsModule,
        HttpClientTestingModule],
      providers: [
        {provide: PostService, useValue: mockPostService},
        {provide: Location, useValue: mockLocationService},
        {provide: Router, useValue: {navigate: () => true}}]
    })
      .compileComponents();
  }));

You did not provide the RouterTestingModule with any valid routes, so it is telling you it has no idea how to route to 'post/view'. 您没有为RouterTestingModule提供任何有效的路由,因此它告诉您不知道如何路由到“发布/查看”。 Change your import of RouterTestingModule to something like the following: 将RouterTestingModule的导入更改为如下所示:

RouterTestingModule.withRoutes([
  { path: 'post/view', component: BlankComponent },
])

Where BlankComponent is an empty component just for testing purposes. 其中BlankComponent是一个空组件,仅用于测试目的。

Here is a working StackBlitz showing this solution. 这是显示此解决方案的工作StackBlitz To recreate your error, simply comment out the RouterTestingModule declaration I changed, and uncomment out the original one without routes just below it in the Stackblitz. 要重新创建您的错误,只需注释掉我更改过的RouterTestingModule声明,然后取消注释掉原来的注释,而在Stackblitz中就没有下面的路由。

I agree the docs are not great on this - the main testing documentation simply states there will be a future document describing the RouterTestingModule in more detail. 我同意这些文档不是很好-主要的测试文档只是声明将来会有一个文档详细描述RouterTestingModule。 See the API info here , it gives an example at the end of the usage withRoutes. 请参阅此处的API信息,它在withRoutes用法的最后给出了一个示例。

I hope this helps. 我希望这有帮助。 :) :)

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

相关问题 Angular 单元测试:错误:无法匹配任何路由 - Angular Unit testing : Error: Cannot match any routes Angular 单元测试:错误:无法匹配任何路由。 URL 段:&#39;home/advisor&#39; - Angular Unit testing : Error: Cannot match any routes. URL Segment: 'home/advisor' 无法匹配任何路线。 角度误差? - Cannot match any routes. Error in angular? 无法匹配任何路线Angular 6上的错误 - Cannot match any routes Error on Angular 6 错误:无法匹配 Angular 5 中的任何路由 - Error: Cannot match any routes in Angular 5 Angular 路由错误:无法匹配任何路由 - Angular Routing Error: Cannot match any routes 错误:无法匹配Angular 4中的任何路线 - Error: Cannot match any routes in Angular 4 Angular 2收到“错误:无法匹配任何路线:” - Angular 2 getting “Error: Cannot match any routes: ''” 角单元测试:未捕获错误:未捕获(承诺中):错误:无法匹配任何路线。 网址段:“注销” - Angular Unit Test: Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'logout' Angular 测试:未捕获错误:未捕获(承诺中):错误:无法匹配任何路由。 URL 段:“家” - Angular Testing: Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'home'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM