我正在学习Jasmin和业力的测试用例。我做了一个角度服务,更新了数据库中的一些记录。我以前创建过测试用例,实际上并不是专家,但从来没有创建过更新数据库的方法。
这是我的基本服务,只有一种方法:
import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
@Injectable({
providedIn: 'root'
})
export class WordsService {
constructor(protected http: HttpClient) {}
associate(uuid: string, item):any {
const url = 'update/associate' + uuid;
this.http.put(url, item).subscribe(response => {
return response;
}, error => {
console.log(error)
});
}
}
我的测试看起来像这样。
describe('WordsService', () => {
let httpMock: HttpTestingController;
let ordsService: WordsService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [WordsService]
});
});
httpMock = getTestBed().get(HttpClientTestingModule);
sentimentTuningService = getTestBed().get(SentimentTuningService);
it('should be updated', inject([SentimentTuningService], async(service: WordsService) => {
expect(service).toBeTruthy();
let mockWordId: string = "37945b85-f6a8-45fd-8864-f45f55df8c78";
let mockData = {
label: "My Cool label",
word_config: "c836468f-1fb4-4339-b5a1-ebf72aa1c6a5",
uuid: "37945b85-f6a8-45fd-8864-f45f55df8c78",
};
WordsService.associate(mockWordId, mockData)
.subscribe(result => {
expect(result.status).toBe(201);
});
}));
});
我不确切地知道如何伪造/模拟数据库中的更新,实际上,我不知道我是否以正确的方式。
显然,我的测试运行出现问题。
你能帮我告诉我如何测试这项服务吗?
单元测试通常不包括单元如何与数据库交互,这更像是e2e测试(量角器)的领域。单元测试更多的意思是“我得到了这个,我生产这个或者用这种方式做出反应”。所有的IO都应该在这个级别上伪造。
有许多很好的资源链接可供使用,建议使用间谍和嘲笑。如果你的服务正在调用httpClient,它不应该测试来自httpClient的动作IO,而是测试它对httpClient提供的I或O的反应(如果我以一种有意义的方式说的话)。
一个基本的剪辑(可能需要调整):
// inside of test
const spy = spyOn(httpClient, 'get').and.callThrough();
... call method
expect(spy).toHaveBeenCalled()
// or
const spy = spyOn(httpClient, 'get').and.callThrough();
... call method with <values>
expect(spy).toHaveBeenCalledWith(<values>)