jest错误 TS18047 “对象可能为null”

huangapple go评论151阅读模式
英文:

jest error TS18047 "object is possible null"

问题

以下是翻译好的部分:


我正在为一个 Angular 组件编写一个测试(jtest),但由于这个错误而失败了。
有什么想法吗? jest错误 TS18047 “对象可能为null”


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? jest错误 TS18047 “对象可能为null”


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:

error stacktrace

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();
    });

现在对我有效,无论如何谢谢 jest错误 TS18047 “对象可能为null”

英文:

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 jest错误 TS18047 “对象可能为null”

huangapple
  • 本文由 发表于 2023年6月19日 14:49:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76504237.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定