在单元测试中,表单报告为有效,但在常规环境中无效

In unit test a form is reporting as valid, but not in regular environment

我有一个测试失败了,因为在测试环境中,一个按钮在应该被禁用时没有被禁用。我可以使用这个简单的代码重现它:

<form #submissionForm="ngForm" novalidate>
<input
  type="text"
  ngModel
  required
  id="questionAnswer"
  name="questionAnswer"
>
{{ submissionForm.valid }}
<button [disabled]="!submissionForm.valid">Submit</button>
</form>

在测试中,submissionForm.validtrue;然而,在 运行 代码中它正确地报告为 false.

这里是测试的例子:https://stackblitz.com/edit/angular-testing-with-jasmine-mnbymr?file=app/app.component.html

这是一个 运行 应用程序:https://stackblitz.com/edit/angular-v9uxvt?file=src/app/app.component.html

请注意,我没有在堆栈闪电战示例中添加 it() - 我想知道的是为什么 valid 在一个应用程序中为真而 false 在另一个?

首先我要说的是,我完全不明白这里到底发生了什么。这是我所知道的。

Template-driven forms are asynchronous。这会使 template-driven 表单的测试变得更加困难,因为您必须考虑该因素(有些人总是喜欢使用反应式表单的原因之一)。根据我的经验,fixture.whenStable() 很有帮助:

fixture.whenStable()

Get a promise that resolves when the fixture is stable. This can be used to resume testing after events have triggered asynchronous activity or asynchronous change detection.

基本上,您可以将测试 template-driven 表单的代码放在 fixture.whenStable().then() 中,保证表单已初始化并准备好进行交互。

这里是 updated stack blitz 测试正常运行。

This SO post 有助于更多地了解正在发生的事情。