I'd like to test specific methods in my Vue Single File Components using Jest. I'm using Vue 3 with the Composition API, and I would like to use the <script setup> approach but it appears to prevent this.
This works:
Component:
<script>
export default {
setup() {
const testMethod = function(input) {
return input + 1;
};
return { testMethod };
},
};
</script>
Test:
test('should be 2', () => {
expect(TestComponent.setup().testMethod(1)).toBe(2); // success
});
This doesn't work:
Component:
<script setup>
const testMethod = function(input) {
return input + 1;
};
</script>
Test:
test('should be 2', () => {
expect(TestComponent.setup().testMethod(1)).toBe(2); // TypeError: Cannot destructure property 'expose' of 'undefined' as it is undefined.
expect(TestComponent.testMethod(1)).toBe(2); // TypeError: _testComponent.default.testMethod is not a function
});
Is there another way to accomplish this, or is accessing the methods within the component not possible with the <script setup> approach?
Edit: Specifically looking for solutions that don't require mounting the gadget with something like vue-test-utils.
The bindings declared in
<script setup>are hidden by default, but you can expose any of them to the component instance withdefineExpose():Then in your test, access the exposed bindings via
wrapper.vm(the component instance from the@vue/test-utilswrapper):demo