Problem
Inside a component which should render when getPersons
returns with a collection of Persons.
I need to write two tests:
- Which asserts x attribute is available in the HTML
- Which asserts that x attribute is not in the html
In my current test configurations, I can’t mock out the getPersons
return value as an empty [] in order to verify test scenario 2.
Question: How to change the return value from function inside a store?
<div v-if="persons" ref="personList">
<div data-cy="foo">hello world</div>
</div>
store
export const userStore = defineStore("user", {
state: () => ({
fooObject: null
}),
actions: {
async getPersons() {
// get all person
}
}})
user module
import { userStore } from 'somepath'
const { getPersons } = userStore();
onMounted(async () => {
const persons = await getPersons()
})
Component Test
import { useStore } 'somepath'
vi.mock('somepath', () => ({
userStore: vi.fn().mockImplementation(() => ({
getPersons: vi.fn().mockResolvedValue([{name: 'foo'}])
}))
}))
describe("personList Comp", () => {
it("should show all persons", async () => {
const wrapper = mount(Perons, ...options) // pass in createTestingPinia, router etc
const comp = wrapper.findComponent(Persons);
// getPersons will return [{name: 'foo'}]
// and component can conditionally render
})
it("show not show persons if no data", async () => {
// I've tried the following, but when the test runs it always returns an array of persons
vi.mocked(getPersons).mockResolvedValue([])
})