我刚开始用 Jasmine 和 Karma 测试我的软件(还没有做过 E2E 之外的任何单元测试,所以我只是这里的新手)。
我被要求做的是创建一个通用的 API 服务,你每次需要发出 HTTP 请求时调用它,以避免重复代码并加快编程速度。我给你看我已经拥有的东西:
api.service.ts
import { HttpClient, HttpContext, HttpParams } from '@angular/common/http'
import { Injectable } from '@angular/core'
import { Observable } from 'rxjs'
@Injectable({
providedIn: 'root'
})
export class ApiService {
headers: ApiRequests = {
httpHeaderAccept: 'application/json',
context: new HttpContext(),
params: new HttpParams()
}
constructor(private _http: HttpClient) {}
post<T>(url: string, body: object): Observable<T> {
return this._http.post<T>(url, body, { ...this.headers })
}
}
我没有展示其余的 HTTP 方法,因为它们非常相似,POST 在这里就可以了。
现在这是我的 .spec.ts 文件:
import { HttpClient } from '@angular/common/http'
import { TestBed } from '@angular/core/testing'
import { of } from 'rxjs'
import { ApiService } from './api.service'
describe('ApiService', () => {
let service: ApiService
let httpClientSpyPost: {
post: jasmine.Spy
}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
ApiService,
{ provide: HttpClient, useValue: httpClientSpyPost }
]
})
service = TestBed.inject(ApiService)
httpClientSpyPost = jasmine.createSpyObj('HttpClient', ['post'])
})
it('should be created', () => {
expect(service).toBeTruthy()
})
it('(POST) -> should return a response with a body', (done: DoneFn) => {
const body = {}
const expectedResponse = {}
httpClientSpyPost.post.and.returnValue(of(expectedResponse))
service.post('url', body).subscribe((response) => {
expect(response).toEqual(expectedResponse)
done()
})
})
})
这是茉莉花给我的错误:
TypeError: this._http.post is not a function
我真的不知道它的真正含义,我想我已经正确设置了所有内容并尝试了我在这里阅读的一些内容。
import { HttpClient } from '@angular/common/http'
import { TestBed } from '@angular/core/testing'
import { of } from 'rxjs'
import { ApiService } from './api.service'
describe('ApiService', () => {
let service: ApiService
let httpClientSpyPost: {
post: jasmine.Spy
}
beforeEach(() => {
httpClientSpyPost = jasmine.createSpyObj('HttpClient', ['post'])
TestBed.configureTestingModule({
providers: [
ApiService,
{ provide: HttpClient, useValue: httpClientSpyPost }
]
})
service = TestBed.inject(ApiService)
})
it('should be created', () => {
expect(service).toBeTruthy()
})
it('(POST) -> should return a response with a body', (done: DoneFn) => {
const body = {}
const expectedResponse = {}
httpClientSpyPost.post.and.returnValue(of(expectedResponse))
service.post('url', body).subscribe((response) => {
expect(response).toEqual(expectedResponse)
done()
})
})
})
在配置 TestBed 之前尝试分配
httpClientSpyPost
。看起来你传递了 undefined
值,后来你的分配没有效果。
可能是由于创建服务时注入了初始化的间谍对象。
在
service =
行之前初始化间谍对象,或者在调用configureTestModule
之前更安全:
httpClientSpyPost = jasmine.createSpyObj('HttpClient', ['post'])
TestBed.configureTestingModule(
...