AuthGuard错误:无法从同步测试中调用Promise.then



我曾尝试在Angular 10中测试一个保护组件。组件已注入

一条错误消息:";错误:无法从同步测试中调用Promise.then&";。也许有人知道怎么了?

import { TestBed, waitForAsync, async, getTestBed } from '@angular/core/testing';
import { AngularFireModule } from '@angular/fire';
import { AuthGuard } from './auth.guard';
import { AuthService } from '../shared/services/auth.service';
import { ActivatedRouteSnapshot, Router } from '@angular/router';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { environment } from '../../environments/environment';
describe('AuthGuard', () => {
let guard: AuthGuard;
let injector: TestBed;
let authService: AuthService;
const routerMock = {navigate: jasmine.createSpy('chats')};
beforeEach(() => {
TestBed.configureTestingModule({
providers: [AuthGuard, { provide: Router, useValue: routerMock }],
imports: [
HttpClientTestingModule,
AngularFireModule.initializeApp(environment.firebaseConfig)
]
}).compileComponents();
guard = TestBed.inject(AuthGuard);
});
injector = getTestBed();
authService = injector.inject(AuthService);
guard = injector.inject(AuthGuard);
it('should be created', () => {
expect(guard).toBeTruthy();
});

it('should redirect an unauthenticated user to the login route', waitForAsync(() => {
const promise = new Promise(() => {});
promise.then(() => {
expect(authService.SignOut).toBeTruthy();
});
}));
it('should allow the authenticated user to access app', waitForAsync(() => {
const promise = new Promise(() => {});
promise.then(() => {
expect(authService.isLoggedIn).toBe(true);
});
}));
});

你能帮我吗,谢谢

简而言之:您应该将routerMock的初始化移到beforeEach((块中。

这个问题已经讨论过了:单元测试错误:无法从同步测试中调用Promise.then

最新更新