Coming soon - Get a detailed view of why an account is flagged as spam!
view details

This post has been de-listed

It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.

2
Proper way to test vuex actions that return a promise
Post Body

Testing components with Vue.js actions

I'm comfortable with Vue.js but tests have been a struggle for me. I always seem to run into problems when something involves Promises. Right now I'm testing a basic component that dispatches a Vue.js action.

Something like

<template>
  <div>
    <button @click="create"></button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      someval: 0
    }
  },
  methods: {
    create() {
      this.$store.dispatch('create-event').then((res) => {
        this.someval  ;
      }).catch((err) => { logError(); });
    }
  }
}
</script>

And my test checks the interaction of the button, and that the correct response is called.

describe('Create stuff', () => {
  beforeEach(() => {
    // more testing setup stuff here
    actions = {
      'create-event': sinon.fake()
    };
    // store uses these actions
  });

  it('creates stuff when submitted', () => {
    const wrapper = shallowMount(CreateStuff, { store });
    const button = wrapper.find('button');
    button.vm.$emit('click');

    assert.isTrue(actions['create-event'].calledOnce); // passes
    assert.equal(wrapper.vm.someval, 1); // fails
  });
}

I'm following the vue-test-utils guidelines to mock my actions. I've tried using sinon.fake.resolves() to resolve the action with a Promise. I've tried wrapping things in nextTick. But no matter what I do the "this.someval " never gets called until after the test is over.

Should I be mocking the entire $store.dispatch? This was my initial instinct, but all the Vuex and testing guides seem to want me to mock the actions themselves.

What's the proper way to test components with vuex actions that return a promise?

Author
Account Strength
60%
Account Age
11 years
Verified Email
No
Verified Flair
No
Total Karma
578
Link Karma
339
Comment Karma
239
Profile updated: 3 days ago
Posts updated: 6 months ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
5 years ago