0

I'm using a Vue composable to return an sequential number that is used to generate a unique ID for components e.g. for aria-controls.

/** Composable to return a sequential number */
import { onMounted, ref } from '@vue/composition-api'

/** Define a starting integer */
const globalItemNumber = ref(0)

/**
 * Increment and return the global item number
 */
export function useSequentialNumber() {
    const localItemNumber = ref(0)

    onMounted(() => (localItemNumber.value = globalItemNumber.value++))

    return { itemNumber: localItemNumber }
}

I've written a test for this script but when I run it I get the following error:

 ● Test suite failed to run
@serenity-web/common-helpers:     [vue-composition-api] must call Vue.use(VueCompositionAPI) before using any function.
@serenity-web/common-helpers:       3 |
@serenity-web/common-helpers:       4 | /** Define a starting integer */
@serenity-web/common-helpers:     > 5 | const globalItemNumber = ref(0)

How do I solve this problem? Is it best to abstract the global variable outside of my composable or is there a way of mocking it in the test script?

1
  • I gave up trying to get this to work. Adding vue/composition-api to Jest config caused a load of new errors when the test suite ran. The original reason for the change was so that we could generate a unique ID for our components. We could use this library (npmjs.com/package/vue-unique-id) but it's been written for Vue 2 and we're running Vue 3. In the end, I just kept the logic in the component rather than using a composable which we're able to test using createLocalVue from @vue/test-utils Commented Feb 17, 2022 at 9:11

1 Answer 1

1

The problem is specific to Vue 2, where composition API is available via @vue/composition-api plugin. The error means what it says, it's necessary to execute Vue.use(VueCompositionAPI) before using composition API.

It's likely the same in the app itself but may require to treat it in a special way in tests. This requires to have the module:

Vue.use(VueCompositionAPI);

And import it before anything else, specifically modules that use composition API on import (outside setup function):

import '.../composition-plugin';
...

This needs to be done for both application entry point and tests. This can be done once for all test suites in setupFiles.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Estus, do you know of any guides for configuring this in Jest?
I've done this but it still throws the same error for me
This most likely means that the file wasn't imported. You can confirm this by adding syntax error there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.