簡體   English   中英

角單元測試:未捕獲錯誤:未捕獲(承諾中):錯誤:無法匹配任何路線。 網址段:“注銷”

[英]Angular Unit Test: Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'logout'

啟用我的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();
  });
});

您有一個錯誤,因為即使您在此處使用RouterTestingModule也沒有配置路由。 如下配置規范的imports部分,但我認為在onInit調用logout功能不是正確的實現。

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

告訴我這是否可行,我們將從那里找出。 我認為,即使這解決了您的問題,也很難測試您的測試用例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM