角单元测试:未捕获错误:未捕获(承诺中):错误:无法匹配任何路线。网址段:“注销”

时间:2019-03-25 10:47:53

标签: javascript angular unit-testing mocking karma-jasmine

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

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

login.component.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();
  });
});

1 个答案:

答案 0 :(得分:1)

您有一个错误,因为即使您在此处使用RouterTestingModule,也没有配置路由。按如下所示配置规范的imports部分,但我认为在logout上调用onInit函数是不适当的实现。

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

告诉我这是否可行,我们将从那里弄清楚。我认为,即使这解决了您的问题,也几乎无法测试您的测试用例。