У меня есть провальный тест, который я не уверен, как исправить. Сообщения об ошибках, которые я получаю от Jest, кажутся противоречивыми, и проблема связана с поведением двух Angular HttpTestingController методов: verify()
и expectOne()
.
Тест, о котором идет речь, в контексте его файла:
import {TestBed, getTestBed} from '@angular/core/testing';
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
import {PrintProjectsService} from './print-projects.service';
import {AppConfig} from '../../app.config';
describe('PrintProjectsService', () => {
let injector: TestBed;
let service: PrintProjectsService;
let appConfig: AppConfig;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [PrintProjectsService, AppConfig]
});
injector = getTestBed();
service = injector.get(PrintProjectsService);
httpMock = injector.get(HttpTestingController);
appConfig = injector.get(AppConfig);
});
afterEach(() => {
httpMock.verify();
});
//This test passes
it('should make a GET request to retrieve a printable factory when provided a printable factory id', () => {
const id = '12345';
service.getPrintableFactory(id).subscribe();
const req = httpMock.expectOne(`${appConfig.API_URL}/api/printed-book/v1/printable-factories/${id}/`);
expect(req.request.method).toBe('GET');
});
// This is the one that fails
it('should make a GET request to retrieve cover image data from the cover service', () => {
const imageType = 'full';
service.getCoverImage(12345, '0850X1100FCSTDCO080CW444GXX', imageType).subscribe();
//httpMock.verify(); //this finds a GET at undefined/cover/api/cover-images/full
const req = httpMock.expectOne(`${appConfig.API_URL}/cover/api/cover-images/${imageType}`);
expect(req.request.responseType).toBe('blob');
});
});
Jest возвращает это сообщение об ошибке:
● PrintProjectsService › should make a GET request to retrieve cover image data from the cover service
Expected one matching request for criteria "Match URL: undefined/cover/api/cover-images/full", found none.
44 | service.getCoverImage(12345, '0850X1100FCSTDCO080CW444GXX', imageType).subscribe();
> 45 | const req = httpMock.expectOne(`${appConfig.API_URL}/cover/api/cover-images/${imageType}`);
46 | expect(req.request.responseType).toBe('blob');
at HttpClientTestingBackend.Object.<anonymous>.HttpClientTestingBackend.expectOne (node_modules/@angular/common/bundles/common-http-testing.umd.js:435:19)
at src/app/services/print-projects/print-projects.service.spec.ts:45:26
...
at Object.testBody.length (node_modules/jest-zone-patch/index.js:50:27)
● PrintProjectsService › should make a GET request to retrieve cover image data from the cover service
Expected no open requests, found 1: GET undefined/cover/api/cover-images/full
23 | afterEach(() => {
> 24 | httpMock.verify();
25 | });
Тот факт, что переменные URL отображаются в undefined
в сообщениях об ошибках, не имеет значения - это относится и к прохождению тестов.
Что меня смущает, так это то, что когда в тесте достигается expectOne()
, запрос для undefined/cover/api/cover-images/full
не может быть найден, но после теста verify()
находит GET-запрос по идентичному URL : undefined/cover/api/cover-images/full
. verify()
также находит GET-запрос на undefined/cover/api/cover-images/full
, если поместить его в строку теста до expectOne()
.
Почему expectOne()
не ловит запрос, а verify()
делает? Сообщение об ошибке не говорит мне все, что мне нужно? Кажется, я получаю одни и те же сообщения об ошибках независимо от того, запускаю я jest
или jest --verbose
.