Skip to content

Commit

Permalink
feat(testing): allows faking an app
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed Jun 28, 2021
1 parent 10bef8a commit 0d00a27
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
21 changes: 21 additions & 0 deletions __tests__/testing.spec.ts
Expand Up @@ -117,4 +117,25 @@ describe('Testing', () => {
expect(counter.$patch).toHaveBeenLastCalledWith({ n: 1 })
expect(counter.n).toBe(0)
})

it('executes plugins', () => {
const { counter, wrapper } = factory({
plugins: [() => ({ pluginN: 0 })],
})

expect(counter.pluginN).toBe(0)
expect(wrapper.vm.counter.pluginN).toBe(0)
})

it('executes plugins with fakeApp', () => {
const pinia = createTestingPinia({
plugins: [() => ({ pluginN: 0 })],
fakeApp: true,
})

const counter = useCounter(pinia)

expect(counter.pluginN).toBe(0)
expect(pinia.app).toHaveProperty('mount', expect.any(Function))
})
})
28 changes: 27 additions & 1 deletion src/testing.ts
@@ -1,9 +1,11 @@
import { App, createApp } from 'vue'
import { createPinia } from './createPinia'
import { Pinia, PiniaStorePlugin, setActivePinia } from './rootStore'

export interface TestingOptions {
/**
* Plugins to be installed before the testing plugin.
* Plugins to be installed before the testing plugin. Add any plugins used in
* your application that will be used while testing.
*/
plugins?: PiniaStorePlugin[]

Expand All @@ -20,6 +22,18 @@ export interface TestingOptions {
*/
stubPatch?: boolean

/**
* Creates an empty App and calls `app.use(pinia)` with the created testing
* pinia. This is allows you to use plugins while unit testing stores as
* plugins **will wait for pinia to be installed in order to be executed**.
* Defaults to false.
*/
fakeApp?: boolean

/**
* Function used to create a spy for actions and `$patch()`. Pre-configured
* with `jest.fn()` in jest projects.
*/
createSpy?: (fn?: (...args: any[]) => any) => (...args: any[]) => any
}

Expand All @@ -28,6 +42,9 @@ export interface TestingPinia extends Pinia {
* Clears the cache of spies used for actions.
*/
resetSpyCache(): void

/** App used by Pinia */
app: App
}

/**
Expand All @@ -45,6 +62,7 @@ export function createTestingPinia({
plugins = [],
stubActions = true,
stubPatch = false,
fakeApp = false,
createSpy,
}: TestingOptions = {}): TestingPinia {
const pinia = createPinia()
Expand Down Expand Up @@ -80,13 +98,21 @@ export function createTestingPinia({
store.$patch = stubPatch ? createSpy!() : createSpy!(store.$patch)
})

if (fakeApp) {
const app = createApp({})
app.use(pinia)
}

setActivePinia(pinia)

return Object.assign(
{
resetSpyCache() {
spiedActions.clear()
},
get app() {
return this._a as App
},
},
pinia
)
Expand Down

0 comments on commit 0d00a27

Please sign in to comment.