首页 > 解决方案 > 角度单元测试:未捕获错误:未捕获(承诺):错误:无法匹配任何路由。URL 段:“注销”

问题描述

当我启用 login.spec.ts 测试时,我总是在不同的测试中随机出现此错误。 未捕获的错误:未捕获(承诺):错误:无法匹配任何路由。URL 段:“注销”

我尝试使用以下方法伪造 authService 中的注销方法: spyOn(authService, 'logout').and.returnValues(true); 但它仍然不起作用。请帮助解决这里的问题。

登录组件.ts

export class LoginComponent implements OnInit {

  isLoggingIn = false;
  constructor(
    private authService: AuthService
  ) { }

  ngOnInit() {
    this.authService.logout();
  }
}

authService.ts

@Injectable()
export class AuthService {

  public userSource: BehaviorSubject<string | undefined> = new BehaviorSubject<string | undefined>(undefined);

  constructor(
    private myRoute: Router) {
    }
  logout() { // TODO: Right now this is fake logout. We need to either destroy express session or cookie.
    this.userSource.next(undefined);
    this.myRoute.navigate(['logout']);
  }
}

现在我的

login.component.spec.ts

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      providers: [ AuthService,
        ConfigService
      ],
      imports: [ RouterTestingModule,
      HttpClientTestingModule ]
    })
    .compileComponents();
  }));

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

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

标签: javascriptangularunit-testingmockingkarma-jasmine

解决方案


你有一个错误,因为即使你在RouterTestingModule这里使用过,你也没有配置路由。如下配置您imports的规范部分,但我认为调用logout函数不是onInit正确的实现。

imports: [
   RouterTestingModule.withRoutes([
          { path: 'logout', component: LogoutComponent }
   ]),
   HttpClientTestingModule
]

告诉我这是否有效,我们会从那里弄清楚。我认为即使这可以解决您的问题,它也很难测试您的测试用例。


推荐阅读