我如何在Angular中测试一个需要TranslateService的helper方法的组件?



我有一个使用ngx-translate的自定义Validator

export class CustomValidator {
static translation: TranslateService;
static setTranslationService( translation: TranslateService): void {
CustomValidator.translation = translation;
}
static required(messageKey: string = 'COMMON.VALIDATORS.REQUIRED') {
const message = this.translation.instant(messageKey);
return (control: AbstractControl): ValidationErrors | null => {
return control.value ? null : { required: message };
};
}
}

我正在我的app.component中设置translateService,像这样:

export class AppComponent implements OnInit, AfterViewInit {
constructor(private translateService: TranslateService) { }
ngOnInit() {
CustomValidator.setTranslationService(this.translateService);
}
}

可以工作,但是当测试任何使用CustomValidator的组件时,我得到一个错误:

TypeError: Cannot read properties of undefined (reading 'instant')

我已经尝试创建一个MockCustomValidator类并将其添加为提供者

describe('MainLayoutComponent', () => {
let component: MainLayoutComponent;
let fixture: ComponentFixture<MainLayoutComponent>;

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
TranslateTestingModule.withTranslations({
en: require('../../../../../assets/i18n/en.json'),
})
], providers: [
{ provide: CustomValidator, useClass: MockCustomValidator }
]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MainLayoutComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
}

,但仍然会抛出错误。知道我该怎么做吗?

我设法解决了这个问题,不是通过模拟自定义验证器,而是通过用一个即时方法模拟TranslateService,并对我的测试进行以下更改:

describe('MainLayoutComponent', () => {
let component: MainLayoutComponent;
let fixture: ComponentFixture<MainLayoutComponent>;

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
TranslateTestingModule.withTranslations({
en: require('../../../../../assets/i18n/en.json'),
})
]
}).compileComponents();
});
beforeEach(() => {
CustomValidator.setTranslationService(new MockTranslateService());
fixture = TestBed.createComponent(MainLayoutComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
}

缺点是,在CustomValidator中,我必须将类型从TranslateService更改为any类型,以便能够设置模拟类

相关内容

  • 没有找到相关文章

最新更新