I have a unique custom Validator that utilizes ngx-translate
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 };
};
}
}
I am configuring the translateService in my app.component, as follows:
export class AppComponent implements OnInit, AfterViewInit {
constructor(private translateService: TranslateService) { }
ngOnInit() {
CustomValidator.setTranslationService(this.translateService);
}
}
This setup works seamlessly. However, when I attempt to test a component utilizing the CustomValidator, an error is triggered:
TypeError: Cannot read properties of undefined (reading 'instant')
In order to address this issue, I experimented with creating a MockCustomValidator and including it as a provider
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();
});
}
Unfortunately, the error persists. Any suggestions on the best approach to resolve this?