角度单位测试:未捕获错误:未捕获(在承诺中):错误:无法匹配任何路由。网址细分:'退出'

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

当我启用login.spec.ts测试时,我总是随机地为不同的测试获取此错误。未捕获错误:未捕获(在承诺中):错误:无法匹配任何路由。网址细分:'退出'

我尝试使用以下命令伪造authService中的logout方法: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();
  });
});
javascript angular unit-testing mocking karma-jasmine
1个回答
1
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.