【发布时间】:2018-03-20 22:16:01
【问题描述】:
我正在尝试在 Pipe 的单元测试中模拟一项服务。我面临的问题是,即使遵循了多个指南并使用了多种方法,我在执行测试时仍然会收到 TypeError: Cannot read property 'transformDateToApi' of undefined 错误。
我见过其他人在组件上执行此任务,但对于 Pipe,它略有不同,对吧?
date.pipe.spec.ts
import { TestBed } from '@angular/core/testing';
import { DatePipe } from './date.pipe';
import { DateFormat } from '@app/enums';
import { ApiService } from '@app/services';
import { MainService } from '@app/state';
class MockApiService extends ApiService {
transformDateToApi(date: Date = new Date()): string {
return '13-08-1996T22:10:32';
}
}
describe('DatePipe', () => {
const testDate = new Date('13-08-1996T22:10:32');
const testDateAsString = '13-08-1996 22:10:32';
const pipe = new DatePipe();
let apiService: ApiService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: ApiService, useClass: MockApiService },
{ provide: MainService, useValue: {} }
]
});
apiService = TestBed.get(ApiService);
});
// Date object test
it('date (as Date object) will be properly transformed in DateFormat.Xshort format', () => {
expect(pipe.transform(testDate, DateFormat.Xshort)).toBe('13-08-\'96');
});
it('date (as Date object) will be properly transformed in DateFormat.Short format', () => {
expect(pipe.transform(testDate, DateFormat.Short)).toBe('13-08-1996');
});
it('date (as Date object) will be properly transformed in DateFormat.Pretty format', () => {
expect(pipe.transform(testDate, DateFormat.Pretty)).toBe('13 augustus 1996');
});
it('date (as Date object) will be properly transformed in DateFormat.WithTime format', () => {
expect(pipe.transform(testDate, DateFormat.WithTime)).toBe('13 augustus 1996 22:10:32');
});
});
date.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { ApiService } from '@app/services';
import { DateFormat } from '@app/enums';
import { DateSegments } from '@app/interfaces';
@Pipe({
name: 'formatDate'
})
export class DatePipe implements PipeTransform {
private date: DateSegments;
constructor (
private apiService: ApiService
) { }
transform(date: Date | string, format: DateFormat = DateFormat.Pretty): string {
if ( date instanceof Date ) {
console.log(this.apiService);
console.log(ApiService);
date = this.apiService.transformDateToApi(date);
}
..... (irrelevant code to this question)
我收到的错误是TypeError: Cannot read property 'transformDateToApi' of undefined。
此时,我的试错策略又回到了将代码拼凑在一起的策略,这种策略并没有教给我任何东西。
【问题讨论】:
标签: angular unit-testing karma-jasmine