角单元测试:未捕获错误:未捕获(承诺):错误:无法匹配任何路线.网址段:“注销" [英] Angular Unit Test: Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'logout'

查看:79
本文介绍了角单元测试:未捕获错误:未捕获(承诺):错误:无法匹配任何路线.网址段:“注销"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am always getting this error randomly for differennt tests when I enable my login.spec.ts tests. Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'logout'

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

I tried to fake the logout method in authService using: spyOn(authService, 'logout').and.returnValues(true); But still it doesnt work. Please help figuring out the issue here.

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']);
  }
}

现在是我的

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函数不是正确的实现.

You have an error because you haven't configured the routes even you have used RouterTestingModule here. Configure your imports section of the spec as follows but I don't think calling logout function at the onInit is a proper implementation.

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

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

Tell me if this works, and we'll figure out from there. I think even if this fix your problem It hardly test your test case.

这篇关于角单元测试:未捕获错误:未捕获(承诺):错误:无法匹配任何路线.网址段:“注销"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆