【发布时间】:2021-02-26 18:23:45
【问题描述】:
我正在尝试对输入元素进行“打字”测试。我的目标是在 input 元素中放入一些值,并查看其绑定是否具有 input 的值,并查看我在 input 元素中输入的值。
代码:
app.component:
import { Component } from "@angular/core";
@Component({
selector: "my-app",
template: `
<span>My input: </span>
<input name="name-input" placeholder="Enter name" [(ngModel)]="name" />
`,
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "";
}
测试:
import { TestBed } from "@angular/core/testing";
import { FormsModule } from "@angular/forms";
import { AppComponent } from "./app.component";
describe("AppComponent", () => {
var fixture: any;
var app: AppComponent;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [AppComponent],
imports: [FormsModule]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
app = fixture.componentInstance;
});
it("should create the app", () => {
expect(app).toBeTruthy();
});
it("should type text into input element", () => {
let inputElement = fixture.nativeElement.querySelector(
`input[name='name-input']`
);
inputElement.value = "someValue";
inputElement.dispatchEvent(new Event("input"));
fixture.detectChanges();
expect(app.name).toBe("someValue");
});
});
行后:
inputElement.value = "someValue";
inputElement.dispatchEvent(new Event("input"));
fixture.detectChanges();
预期:app.name 等于“someValue”。 发现:app.name 等于空字符串:“”。
证明它不起作用的堆栈闪电战: https://stackblitz.com/edit/stackoverflow-input-question1q2w3e?
【问题讨论】:
-
那么会发生什么?错误?测试失败?根据stackoverflow.com/q/39582707/3001761,设置值然后触发输入事件在例如github.com/textbook/salary-stats/blob/main/src/app/table/…
-
@jonrsharpe 测试失败,预期:“someValue”,发现:“”。现在我将您的解决方案添加到了 stackblitz(我更新了它)。可以看到测试失败了。
-
把minimal reproducible example在问题中,站外链接应该是补充。
-
@jonrsharpe 但这已经是“可重复的示例”。我在我的电脑上测试了它=> 不起作用。所以我分享了一个 stackblitz 来证明它不起作用并且所有测试都失败了。还可以使用您和 uminder 解决方案更新 stackblitz,以证明这一点。
-
"描述问题。“它不起作用”的描述性不足以帮助人们理解您的问题。相反,请告诉其他读者预期的结果行为应该是。告诉其他读者错误消息的确切措辞是什么,以及产生错误消息的代码行。使用对问题的简短但描述性摘要作为问题的标题。"
标签: angular typescript unit-testing testing jasmine