С Angular 7 я могу издеваться над своим SearchService
с Жасмином, создав несколько классов. Первый - это helper.ts
файл, который имеет класс, который вы можете расширить.
/// <reference path="../../../../../node_modules/@types/jasmine/index.d.ts"/>
export interface GuinessCompatibleSpy extends jasmine.Spy {
/** By chaining the spy with and.returnValue, all calls to the function will return a specific
* value. */
andReturn(val: any): void;
/** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied
* function. */
andCallFake(fn: Function): GuinessCompatibleSpy;
/** removes all recorded calls */
reset();
}
export class SpyObject {
static stub(object = null, config = null, overrides = null) {
if (!(object instanceof SpyObject)) {
overrides = config;
config = object;
object = new SpyObject();
}
const m = {};
Object.keys(config).forEach((key) => m[key] = config[key]);
Object.keys(overrides).forEach((key) => m[key] = overrides[key]);
for (const key in m) {
object.spy(key).andReturn(m[key]);
}
return object;
}
constructor(type = null) {
if (type) {
for (const prop in type.prototype) {
let m = null;
try {
m = type.prototype[prop];
} catch (e) {
// As we are creating spys for abstract classes,
// these classes might have getters that throw when they are accessed.
// As we are only auto creating spys for methods, this
// should not matter.
}
if (typeof m === 'function') {
this.spy(prop);
}
}
}
}
spy(name) {
if (!this[name]) {
this[name] = this._createGuinnessCompatibleSpy(name);
}
return this[name];
}
prop(name, value) { this[name] = value; }
/** @internal */
_createGuinnessCompatibleSpy(name): GuinessCompatibleSpy {
const newSpy: GuinessCompatibleSpy = <any>jasmine.createSpy(name);
newSpy.andCallFake = <any>newSpy.and.callFake;
newSpy.andReturn = <any>newSpy.and.returnValue;
newSpy.reset = <any>newSpy.calls.reset;
// revisit return null here (previously needed for rtts_assert).
newSpy.and.returnValue(null);
return newSpy;
}
}
Вот search.service.ts
Я пытаюсь проверить:
@Injectable({
providedIn: 'root'
})
export class SearchService {
constructor(private http: HttpClient) { }
getAll() {
return this.http.get('assets/data/people.json');
}
search(q: string): Observable<any> {
// implementation
}
get(id: number) {
// implementation
}
save(person: Person) {
// implementation
}
}
А вот мойsearch.service.mock.ts
:
import { SpyObject } from './helper';
import { SearchService } from '../search.service';
import Spy = jasmine.Spy;
export class MockSearchService extends SpyObject {
getAllSpy: Spy;
getByIdSpy: Spy;
searchSpy: Spy;
saveSpy: Spy;
fakeResponse: any;
constructor() {
super(SearchService);
this.fakeResponse = null;
this.getAllSpy = this.spy('getAll').andReturn(this);
this.getByIdSpy = this.spy('get').andReturn(this);
this.searchSpy = this.spy('search').andReturn(this);
this.saveSpy = this.spy('save').andReturn(this);
}
subscribe(callback: any) {
callback(this.fakeResponse);
}
setResponse(json: any): void {
this.fakeResponse = json;
}
}
А потом я проверяю это в тесте.
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SearchComponent } from './search.component';
import { MockSearchService } from '../shared/search/mocks/search.service';
import { MockActivatedRoute, MockRouter } from '../shared/search/mocks/routes';
import { SearchService } from '../shared';
import { ActivatedRoute, Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { FormsModule } from '@angular/forms';
describe('SearchComponent', () => {
let component: SearchComponent;
let fixture: ComponentFixture<SearchComponent>;
let mockSearchService: MockSearchService;
let mockActivatedRoute: MockActivatedRoute;
beforeEach(async(() => {
mockSearchService = new MockSearchService();
mockActivatedRoute = new MockActivatedRoute({'term': 'peyton'});
TestBed.configureTestingModule({
declarations: [ SearchComponent ],
providers: [
{provide: SearchService, useValue: mockSearchService},
{provide: ActivatedRoute, useValue: mockActivatedRoute}
],
imports: [FormsModule, RouterTestingModule]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SearchComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
Это работает с Angular 7. Однако, когда я пробую это с Angular 9, я долженудалите // <reference path="..."/>
вверху helper.ts
, чтобы исправить некоторые ошибки компилятора.
ERROR in node_modules/@types/jasmine/index.d.ts:25:1 - error TS6200: Definitions of the following identifiers conflict with those in another file: ImplementationCallback, Func, Constructor, ExpectedRecursive, Expected, SpyObjMethodNames, CustomEqualityTester, CustomMatcherFactory, ExpectationFailed, SpecFunction, SpyObj, jasmine
25 type ImplementationCallback = jasmine.ImplementationCallback;
~~~~
Затем я получаю две ошибки:
Chrome 78.0.3904 (Mac OS X 10.15.1) SearchComponent should create FAILED
Failed: this.getSpy is not a function
at <Jasmine>
И:
NullInjectorError: R3InjectorError(DynamicTestModule)[SearchService -> HttpClient -> HttpClient]:
NullInjectorError: No provider for HttpClient!
error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'SearchService', 'HttpClient', 'HttpClient' ] })
Есть идеи, почему это работает в Angular 7, а не в Angular 9?
Приложение, которое работает с Angular 7, находится на GitHub по адресу https://github.com/mraible/ng-demo.