英文:
jest error TS18047 "object is possible null"
问题
以下是翻译好的部分:
我正在为一个 Angular 组件编写一个测试(jtest),但由于这个错误而失败了。
有什么想法吗?
it("应该要求有效的电子邮件", () => {
spectator.component.email.setValue({ email: "invalidemail" });
expect(spectator.component.email).toEqual(false);
});
来自我的 .ts 文件:
get email(): AbstractControl | null {
return this.form.get("email");
}
以及我的错误:
我尝试过这个 spectator.component.email("invalidemail");
英文:
I'm writing a test (jtest) for an angular component, but is failing because of this error.
any idea?
it("should require valid email", () => {
spectator.component.email.setValue({ email: "invalidemail" });
expect(spectator.component.email).toEqual(false);
});
from my .ts file:
get email(): AbstractControl | null {
return this.form.get("email");
}
and my error:
I've tried this spectator.component.email("invalidemail");
答案1
得分: 0
错误告诉您 this.form
未定义。因此,您必须首先对其进行初始化:
it("应该要求有效的电子邮件", () => {
spectator.component.form = new FormGroup({ email: new FormControl() });
spectator.component.email.setValue({ email: "invalidemail" });
expect(spectator.component.email).toEqual(false);
});
英文:
The error tells you this.form
is undefined. So you have to init it first:
it("should require valid email", () => {
spectator.component.form = new FormGroup({email: new FormControl()});
spectator.component.email.setValue({ email: "invalidemail" });
expect(spectator.component.email).toEqual(false);
});
答案2
得分: 0
解决了...
it("当模式无效时应为无效电子邮件", () => {
spectator.detectChanges();
spectator.component.form.get("email")?.setValue("invalidemail");
spectator.component.form.get("email")?.updateValueAndValidity();
expect(spectator.component.email?.invalid).toBeTruthy();
expect(spectator.component.email?.hasError("pattern")).toBeTruthy();
});
现在对我有效,无论如何谢谢
英文:
well it's resolved...
it("should be invalid email when invalid pattern", () => {
spectator.detectChanges();
spectator.component.form.get("email")?.setValue("invalidemail");
spectator.component.form.get("email")?.updateValueAndValidity();
expect(spectator.component.email?.invalid).toBeTruthy();
expect(spectator.component.email?.hasError("pattern")).toBeTruthy();
});
that is working for me now, thank you anyway
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论