vuejs / pinia

🍍 Intuitive, type safe, light and flexible Store for Vue using the composition api with DevTools support
https://pinia.vuejs.org
MIT License
12.91k stars 1.02k forks source link

Unable to test setup store actions with watcher #2581

Closed bearguns closed 6 months ago

bearguns commented 6 months ago

Reproduction

https://github.com/bearguns/pinia-setup-store-testing-bug

Steps to reproduce the bug

  1. cd into project and install dependencies with $ yarn
  2. Run tests: $ yarn vitest

Expected behavior

Test should pass as spied function is called by watcher, and tallies value is updated correctly.

Actual behavior

Screenshot 2024-02-14 at 11 34 56 AM

Additional information

We use the setup syntax exclusively at my company, but have been unable to get good unit tests going for our Pinia stores, as functions returned from the setup store don't seem to be spied correctly when called from watch, or if called from another function in the setup store.

For example, if I have a store with 2 functions, where one function calls another:

function thing1() {
  if (myValue === true) return thing2();
}

function thing2() {
  console.log("THING 2");
}

Spying on thing2 i.e. const spy = vi.spyOn(store, "thing2") does not work properly. If I call thing1(), my test will fail as the thing2 spy will not record as having been called.

The same behavior occurs if I were to call thing2 from a watcher as shown in the example repo.

posva commented 6 months ago

This is because the inner functions of the store aren’t spied. Only the ones directly called on the store (store.action)