我是 Angular 单元测试的新手,尝试测试 API 访问。
这是我的代码:
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'
import { JwtHelperService, JWT_OPTIONS } from '@auth0/angular-jwt'
import { AuthService } from '../../services/auth.service'
import { UserService } from '../../services/user.service'
import { WorkService } from '../../services/work.service'
import { ErrorToLogService } from '../../services/errorToLog.service'
import { FooterComponent } from './footer.component'
describe('FooterComponent', () => {
let component: FooterComponent
let fixture: ComponentFixture<FooterComponent>
let httpController: HttpTestingController
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
HttpClientTestingModule
],
providers: [
AuthService,
UserService,
WorkService,
ErrorToLogService,
JwtHelperService,
{ provide: JWT_OPTIONS, useValue: JWT_OPTIONS },
],
declarations: [ FooterComponent ]
})
.compileComponents()
})
beforeEach(() => {
fixture = TestBed.createComponent(FooterComponent)
component = fixture.componentInstance
fixture.detectChanges()
httpController = TestBed.inject(HttpTestingController)
})
afterEach(() => {
TestBed.resetTestingModule()
})
it('should create', () => {
expect(component).toBeTruthy()
})
it('Check API returns the webmaster', () => {
let res: string
component.getUserService().getWebmasterEmail().subscribe(
data => res = data,
)
const req = httpController.expectOne({
method: 'GET',
url: `/api/getWebmasterEmail`,
})
req.flush("toto")
expect(res).toEqual("toto")
})
})
测试
Check API returns the webmaster
没有编译因为Variable 'res' is used before being assigned
.
我有点理解,但我不明白为什么它会在这篇文章(测试“应该返回数据”)的“Angular Service Unit Testing Example with HttpClient”段落中工作得更好。
有人能阐明这个问题吗?