Open nemeros opened 2 years ago
In addition to useSlots
, this also happens with useAttrs
, useListeners
, and getCurrentInstance
(using "vue": "~2.7.13"
and "@vue/test-utils" : "1.3.x"
). I cannot run unit tests while using script setup in combination with any one of those methods. Currently using vitest 0.23.4
as the test runner. Also worth noting this happens with mount
as well as shallowMount
.
Quick workaround for vitest (fixes useListeners
usage):
// tests setup
vi.mock('vue', async () => {
const actualModule = await vi.importActual('vue');
return {
...actualModule,
useListeners: actualModule.default.useListeners,
};
});
@rossinek how does this solve the issue? This mock does not change the implementation of useListeners
. The private module variable currentInstance
referenced in getContext
will still be undefined.
Unless mocking prevents inconsistent module resolution. Whilst debugging I've noticed both vitest vue/dist/vue.js
and vue/dist/vue.esm.js
are loaded.
@piktur thank for taking a look at this. It was a long time ago and TBH I don't remember why it works and currently I don't have the capacity to debug it once again but I created a little reproduction for you if you want to dive in. To see the difference run:
npm run test src/components/HelloWorld.broken.spec.js
# vs
npm run test src/components/HelloWorld.spec.js
Any news on this? Some component logic I need to test relies on useSlots
and I still get Cannot read properties of null (reading 'setupContext')
when running the test.
Update for anyone struggling with this: The solution was to put the call to useSlots() into the top-level of your components' script setup block (or setup function). I had placed it inside a function before, heres the before/after example:
Wrong:
<script setup>
const foo = () => {
const accordionItems = useSlots().accordions?.();
# other logic...
}
</script>
Correct:
<script setup>
const accordionItems = useSlots().accordions?.();
const foo = () => {
# other logic...
}
</script>
Currently using:
Subject of the issue
Given a basic component, with setup script, if we use the function
useSlots()
, the component cannot be rendered withmount
.Steps to reproduce
I created a brand new project with create-vue@2, with typescript and vitest :
Now the basic component, SlotComponent.vue :
The associated test, SlotComponent.spec.ts :
Expected behaviour
the test should pass, (it pass if i remove the code
const slots = useSlots()
)Actual behaviour
the test fail with the stacktrace below :
Annex :
my package.json :