Skip to content
Snippets Groups Projects
Verified Commit e7682e3e authored by Erwan Rouchet's avatar Erwan Rouchet
Browse files

Add Pinia plugin for actionsCompleted in unit tests

parent 5e17e11c
No related branches found
No related tags found
1 merge request!1517Add Pinia plugin for actionsCompleted in unit tests
import { assert } from 'chai'
import { cloneDeep, set as lodashSet } from 'lodash'
import { createPinia, setActivePinia } from 'pinia'
import { createApp, markRaw } from 'vue'
import MockAdapter from 'axios-mock-adapter'
import { findHandler } from 'axios-mock-adapter/src/utils'
......@@ -211,3 +213,54 @@ export const StoreTestPlugin = store => {
*/
store.setState = (path, value) => store._withCommit(() => lodashSet(store.state, path, value))
}
/**
* A Pinia store plugin that adds a `.actionsCompleted()` helper to each store and to the Pinia instance,
* allowing to wait for all Pinia actions to finish, successfully or not.
*
* Waiting for `store.actionsCompleted()` will only wait for the actions of this specific store.
* `pinia.actionsCompleted()` will wait for all actions of all stores created with this Pinia instance.
*
* @param {import('pinia').PiniaPluginContext} param0
*/
export function actionsCompletedPlugin ({ pinia, store }) {
store._promises = markRaw([])
store.actionsCompleted = markRaw(() => Promise.allSettled(store._promises))
store.$onAction(({ after, onError }) => {
const promise = new Promise((resolve, reject) => {
// ESLint thinks this after() call is a Mocha after hook and not the Pinia hook
// eslint-disable-next-line mocha/no-top-level-hooks
after(resolve)
onError(reject)
}).finally(() => {
const index = store._promises.indexOf(promise)
if (index >= 0) store._promises.splice(index, 1)
})
store._promises.push(promise)
})
if (!pinia.actionsCompleted) {
pinia.actionsCompleted = markRaw(
() => Promise.allSettled([...pinia._s.values()].map(store => store.actionsCompleted()))
)
}
}
/**
* Set up a Vue app and a Pinia instance with the specified Pinia plugins, for use only in unit tests.
* This should be called before calling any useStore functions.
* Component tests should use `createTestingPinia` from the `@pinia/testing` package instead.
*
* @param {import('pinia').PiniaPlugin[]} plugins Array of plugins to use on the Pinia instance.
* @returns {[import('pinia').Pinia, app: import('vue').App]} The created Pinia instance and Vue app.
*/
export function setUpTestPinia (plugins = []) {
const app = createApp({})
const pinia = createPinia()
app.use(pinia)
setActivePinia(pinia)
plugins.forEach(plugin => pinia.use(plugin))
return [pinia, app]
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment