0
<!-- 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 的用途?

4

1 回答 1

1

wait在实际触发axios呼叫之前,您正在运行。您对click事件的调用必须在wait.

wrapper.find(".button").trigger ("click");
httpMock.wait(() => {
    Vue.nextTick(() => {
        expect(wrapper.html()).toContain("Something wrong here");
        done();
    });
})

另外,我假设您正在导入axios组件,因为我实际上没有看到导入。

于 2017-11-22T22:01:27.290 回答