Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
vuex-mock-store
Advanced tools
Simple and straightforward mock for Vuex v3.x and v4.x (Vue 2 and 3)
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.
npm install -D vuex-mock-store
# with yarn
yarn add -D vuex-mock-store
ℹ️: All examples use Jest API. See 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 = {
global: { $store: store },
// for Vue 2.x: just { $store: store } without global
}
// 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
You can provide a getters
, and state
object to mock them:
const store = new Store({
getters: {
name: 'Eduardo',
},
state: {
counter: 0,
},
})
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
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',
},
})
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
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.
Store
classconstructor(options)
options
state
: initial state object, default: {}
getters
: getters object, default: {}
spy
: interface to create spies. details belowstate
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
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
FAQs
Simple and straightforward mock for Vuex v3.x Store
We found that vuex-mock-store demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.