<!-- template -->
<div>
<textarea v-model="someText">{{someText}}</textarea>
<div v-if="hasError">Something wrong here</div>
<input v-on:click="store" type="submit" value="update" />
</div>
//script
{
data() {
hasError: false,
someText: ""
},
store(){
return axios.post('/my/api/endpoint', { myvalue: this.someText })
.then(() => {
this.hasError= false;
})
.catch(() => {
this.hasError= true;
};
}
}
//test
import { mount } from 'vue-test-utils';
import MyComponent from "./component.vue";
import * as httpMock from 'moxios';
import Vue from "vue";
it("notifies when updates fail", (done) => {
const wrapper = mount(MyComponent);
httpMock.stubFailure("PUT", "/my/api/endpoint",
{
status: 500
});
httpMock.wait(() => {
wrapper.find(".button").trigger ("click");
Vue.nextTick(() => {
expect(wrapper.html()).toContain("Something wrong here");
done();
});
});
我有上面的代码来测试vue应用程序中的错误状态。简单地说,我试图测试一下,如果调用服务器时出错,会显示一些文字。我已经在浏览器中手动测试了这一切并且一切都很好,但我无法对它进行单元测试。它只是失败了,说expected '...' does not contain Something wrong here
可能与dom没有更新有关吗?但我认为这就是Vue.nextTick的用途?
答案 0 :(得分:1)
在您实际触发wait
来电之前,您正在运行axios
。您对click
活动的调用必须在wait
之外。
wrapper.find(".button").trigger ("click");
httpMock.wait(() => {
Vue.nextTick(() => {
expect(wrapper.html()).toContain("Something wrong here");
done();
});
})
另外,我假设您在组件中导入axios
,因为我实际上没有看到导入。