我尝试在更改数据#username
时检查form.username
元素值
// Regitser.vue
...
<div class="form-group">
<label for="username">Username</label>
<input type="text"
class="form-control"
id="username"
v-model="form.username" />
</div>
...
<script>
export default {
name: "RegisterPage",
data: function() {
return {
form: {
username: "",
emailAddress: "",
password: ""
}
};
}
};
</script>
这是测试代码
// Test
describe("RegisterPage.vue", () => {
let wrapper;
let fieldUsername;
let fieldEmailAddress;
let fieldPassword;
let buttonSubmit;
beforeEach(() => {
wrapper = mount(RegisterPage);
fieldUsername = wrapper.find("#username");
fieldEmailAddress = wrapper.find("#emailAddress");
fieldPassword = wrapper.find("#password");
buttonSubmit = wrapper.find('form button[type="submit"]');
});
it("should have form inputs bound with data model", () => {
const username = "sunny";
const emailAddress = "sunny@taskagile.com";
const password = "VueJsRocks!";
wrapper.vm.form.username = username;
wrapper.vm.form.emailAddress = emailAddress;
wrapper.vm.form.password = password;
expect(fieldUsername.element.value).toEqual(username);
expect(fieldEmailAddress.element.value).toEqual(emailAddress);
expect(fieldPassword.element.value).toEqual(password);
});
运行它,它失败了
// Test failed
RegisterPage.vue › should have form inputs bound with data model
expect(received).toEqual(expected) // deep equality
Expected: "sunny"
Received: ""
52 | console.log(wrapper.find("#username").element.value);
53 |
> 54 | expect(fieldUsername.element.value).toEqual(username);
| ^
55 | expect(fieldEmailAddress.element.value).toEqual(emailAddress);
56 | expect(fieldPassword.element.value).toEqual(password);
57 | });
at Object.<anonymous> (tests/unit/RegisterPage.spec.js:54:45)
我在form.username中输入了“ sunny”,但元素未更改 我该如何解决?
答案 0 :(得分:0)
有点晚了,但我到达这里是因为我在阅读“使用 Spring 5 和 VueJS 2 构建应用程序”一书时遇到了这个确切的问题。问题是这本书的代码基于旧版本的 Vue 和 vue-utils,如果你使用了 book repo 中的 package.json,那么事情可能会奏效。
然而,如果你像我一样使用最新的 Vue CLI,那么你最终会在这里! @Estradiaz 在他的评论中是正确的。这是重新设计的测试:
it('should have form inputs bound with data model', async () => {
const username = 'sunny'
const emailAddress = 'sunny@local'
const password = 'VueJsRocks'
await wrapper.setData({
form: {
username: username,
emailAddress: emailAddress,
password: password
}
});
expect(fieldUsername.element.value).toEqual(username)
expect(fieldEmailAddress.element.value).toEqual(emailAddress)
expect(fieldPassword.element.value).toEqual(password)
})