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();
            });
        });

I have the above code to test error state in the vue app. Simply, i'm trying to test that if there is an error calling the server, a bit of text is displayed to say so. i've manually tested this in the browser and its all good, but i can't get a unit test around it. it just fails, saying expected '...' does not contain Something wrong here

probably something to do with the dom not being updated yet? But I thought that was what Vue.nextTick was for?

Daniel
  • 34,125
  • 17
  • 102
  • 150
MartinM
  • 1,736
  • 5
  • 20
  • 33

1 Answers1

1

You're running wait before you actually trigger the axios call. Your call of the click event must be outside of wait.

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

Also, I'm assuming you're importing axios in the component, as I don't actually see the import.

Luis Orduz
  • 2,887
  • 1
  • 13
  • 19
  • This was exactly right. I cut the sample down for simplicity but I was actually loading the initial page async which required the wait. After clicking I needed a second wait, which is what I missed. Thank you! – MartinM Nov 22 '17 at 22:04