All Projects → posva → Vuex Mock Store

posva / Vuex Mock Store

Licence: mit
✅Simple and straightforward Vuex Store mock for vue-test-utils

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Vuex Mock Store

Nx Admin
👍 A magical 🐮 ⚔ vue admin,记得star
Stars: ✭ 2,497 (+915.04%)
Mutual labels:  test, mock, vuex
jest-launchdarkly-mock
Easily unit test LaunchDarkly feature flagged components with jest
Stars: ✭ 14 (-94.31%)
Mutual labels:  mock, jest, test
Mocktopus
Mocking framework for Rust
Stars: ✭ 179 (-27.24%)
Mutual labels:  test, mock
Jest Canvas Mock
🌗 A module used to mock canvas in Jest.
Stars: ✭ 189 (-23.17%)
Mutual labels:  jest, mock
Jest Expect Message
Add custom message to Jest expects 🃏🗯
Stars: ✭ 240 (-2.44%)
Mutual labels:  jest, test
Jest Html Reporter
Jest test results processor for generating a summary in HTML
Stars: ✭ 161 (-34.55%)
Mutual labels:  jest, test
Symfony Vuejs
Source code of the tutorial "Building a single-page application with Symfony 4 and Vue.js"
Stars: ✭ 170 (-30.89%)
Mutual labels:  vuex, store
Buefy Shop
A sample shop built with Nuxt, Stripe, Firebase and Serverless Functions
Stars: ✭ 207 (-15.85%)
Mutual labels:  jest, vuex
Nsubstitute
A friendly substitute for .NET mocking libraries.
Stars: ✭ 1,646 (+569.11%)
Mutual labels:  test, mock
Aspnetcore Vue Typescript Template
Template AspNetCore with Vue, Vue router, Vuex, TypeScript, Bulma, Sass and Jest
Stars: ✭ 215 (-12.6%)
Mutual labels:  jest, vuex
Sinon Jest Cheatsheet
Some examples on how to achieve the same goal with either of both libraries: sinon and jest. Also some of those goals achievable only by one of these tools.
Stars: ✭ 226 (-8.13%)
Mutual labels:  jest, mock
Vue Cli Multi Page
基于vue-cli模板的多页面多路由项目,一个PC端页面入口,一个移动端页面入口,且有各自的路由, vue+webpack+vue-router+vuex+mock+axios
Stars: ✭ 145 (-41.06%)
Mutual labels:  mock, vuex
Javascript Testing Best Practices
📗🌐 🚢 Comprehensive and exhaustive JavaScript & Node.js testing best practices (August 2021)
Stars: ✭ 13,976 (+5581.3%)
Mutual labels:  jest, test
Snap Shot
Jest-like snapshot feature for the rest of us, works magically by finding the right caller function
Stars: ✭ 170 (-30.89%)
Mutual labels:  jest, test
D2 Admin
An elegant dashboard
Stars: ✭ 11,012 (+4376.42%)
Mutual labels:  mock, vuex
Vuesion
Vuesion is a boilerplate that helps product teams build faster than ever with fewer headaches and modern best practices across engineering & design.
Stars: ✭ 2,510 (+920.33%)
Mutual labels:  jest, vuex
Jest Mock Extended
Type safe mocking extensions for Jest https://www.npmjs.com/package/jest-mock-extended
Stars: ✭ 224 (-8.94%)
Mutual labels:  jest, mock
Gest
👨‍💻 A sensible GraphQL testing tool - test your GraphQL schema locally and in the cloud
Stars: ✭ 109 (-55.69%)
Mutual labels:  jest, test
Vue Spa Project
vue.js + vuex + vue-router + fetch + element-ui + es6 + webpack + mock 纯前端SPA项目开发实践
Stars: ✭ 118 (-52.03%)
Mutual labels:  mock, vuex
Vue Blog
🎉 基于vue全家桶 + element-ui 构建的一个后台管理集成解决方案
Stars: ✭ 208 (-15.45%)
Mutual labels:  mock, vuex

vuex-mock-store Build Status npm package coverage thanks

Simple and straightforward mock for Vuex v3.x Store

Automatically creates spies on commit and dispatch so you can focus on testing your component without executing your store code.

Help me keep working on Open Source in a sustainable way 🚀. Help me with as little as $1 a month, sponsor me on Github.

Silver Sponsors

Vue Mastery logo

Vuetify logo

Bronze Sponsors

Storyblok logo


Installation

npm install -D vuex-mock-store
# with yarn
yarn add -D vuex-mock-store

Usage

ℹ️: All examples use below to use a different mock library.

Usage with vue-test-utils:

Given a component MyComponent.vue:

<template>
  <div>
    <p class="count">{{ count }}</p>
    <p class="doubleCount">{{ doubleCount }}</p>
    <button class="increment" @click="increment">+</button>
    <button class="decrement" @click="decrement">-</button>
    <hr />
    <button class="save" @click="save({ count })">Save</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'

export default {
  computed: {
    ...mapState(['count']),
    ...mapGetters(['doubleCount']),
  },
  methods: {
    ...mapMutations(['increment', 'decrement']),
    ...mapActions(['save']),
  },
}
</script>

You can test interactions without relying on the behaviour of your actions and mutations:

import { Store } from 'vuex-mock-store'
import { mount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'

// create the Store mock
const store = new Store({
  state: { count: 0 },
  getters: { doubleCount: 0 },
})
// add other mocks here so they are accessible in every component
const mocks = {
  $store: store,
}

// reset spies, initial state and getters
afterEach(() => store.reset())

describe('MyComponent.vue', () => {
  let wrapper
  beforeEach(() => {
    wrapper = mount(MyComponent, { mocks })
  })

  it('calls increment', () => {
    wrapper.find('button.increment').trigger('click')
    expect(store.commit).toHaveBeenCalledOnce()
    expect(store.commit).toHaveBeenCalledWith('increment')
  })

  it('dispatch save with count', () => {
    wrapper.find('button.save').trigger('click')
    expect(store.dispatch).toHaveBeenCalledOnce()
    expect(store.dispatch).toHaveBeenCalledWith('save', { count: 0 })
  })
})

⚠️ The mocked dispatch method returns undefined instead of a Promise. If you rely on this, you will have to call the appropriate function to make the dispatch spy return a Promise:

store.dispatch.mockReturnValue(Promise.resolve(42))

If you are using Jest, you can check the documentation here

Initial state and getters

You can provide a getters, and state object to mock them:

const store = new Store({
  getters: {
    name: 'Eduardo',
  },
  state: {
    counter: 0,
  },
})

Modules

State

To mock module's state, provide a nested object in state with the same name of the module. As if you were writing the state yourself:

new Store({
  state: {
    value: 'from root',
    moduleA: {
      value: 'from A',
      moduleC: {
        value: 'from A/C',
      },
    },
    moduleB: {
      value: 'from B',
    },
  },
})

That will cover the following calls:

import { mapState } from 'vuex'

mapState(['value']) // from root
mapState('moduleA', ['value']) // from A
mapState('moduleB', ['value']) // from B
mapState('moduleA/moduleC', ['value']) // from C

When testing state, it doesn't change anything for the module to be namespaced or not

Getters

To mock module's getters, provide the correct name based on whether the module is namespaced or not. Given the following modules:

const moduleA = {
  namespaced: true,

  getters: {
    getter: () => 'from A',
  },

  // nested modules
  modules: {
    moduleC: {
      namespaced: true,
      getter: () => 'from A/C',
    },
    moduleD: {
      // not namespaced!
      getter: () => 'from A/D',
    },
  },
}

const moduleB = {
  // not namespaced
  getters: {
    getter: () => 'from B',
  },
}

new Vuex.Store({ modules: { moduleA, moduleC } })

We need to use the following getters:

new Store({
  getters: {
    getter: 'from root',
    'moduleA/getter': 'from A',
    'moduleA/moduleC/getter': 'from A/C',
    'moduleA/getter': 'from A/D', // moduleD isn't namespaced
    'moduleB/getter': 'from B',
  },
})

Actions/Mutations

As with getters, testing actions and mutations depends whether your modules are namespaced or not. If they are namespaced, make sure to provide the full action/mutation name:

// namespaced module
expect(store.commit).toHaveBeenCalledWith('moduleA/setValue')
expect(store.dispatch).toHaveBeenCalledWith('moduleA/postValue')
// non-namespaced, but could be inside of a module
expect(store.commit).toHaveBeenCalledWith('setValue')
expect(store.dispatch).toHaveBeenCalledWith('postValue')

Refer to the module example below using getters for a more detailed example, even though it is using only getters, it's exactly the same for actions and mutations

Mutating state, providing custom getters

You can modify the state and getters directly for any test. Calling store.reset() will reset them to the initial values provided.

API

Store class

constructor(options)

  • options
    • state: initial state object, default: {}
    • getters: getters object, default: {}
    • spy: interface to create spies. details below

state

Store state. You can directly modify it to change state:

store.state.name = 'Jeff'

getters

Store getters. You can directly modify it to change a value:

store.getters.upperCaseName = 'JEFF'

ℹ️ Why no functions?: if you provide a function to a getter, you're reimplementing it. During a test, you know the value, you should be able to provide it directly and be completely sure about the value that will be used in the component you are testing.

reset

Reset commit and dispatch spies and restore getters and state to their initial values

Providing custom spies

By default, the Store will call jest.fn() to create the spies. This will throw an error if you are using mocha or any other test framework that isn't Jest. In that situation, you will have to provide an interface to create spies. This is the default interface that uses jest.fn():

new Store({
  spy: {
    create: handler => jest.fn(handler),
  },
})

The handler is an optional argument that mocks the implementation of the spy.

If you use Jest, you don't need to do anything. If you are using something else like Sinon, you could provide this interface:

import sinon from 'sinon'

new Store({
  spy: {
    create: handler => sinon.spy(handler),
  },
})

commit & dispatch

Spies. Dependent on the testing framework

Related

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].