Search code examples
vue.jskarma-jasminevue-componentaxiosmoxios

Vuejs testing value after click


<!-- 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?


Solution

  • 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.