0

I am using Vue test utils and Typescript. I have added Data Test ID Plugin.

How can I extend VueWrapper interface to avoid this error:

Property 'findByTestId' does not exist on type 'VueWrapper<{ $: ComponentInternalInstance; $data: { showUserMenu: boolean ...
1
  • 1
    The question is unanswerable without package versions of vue, vue-test-utils, jest, typescript and a few more deps, depending on whether you're using @vue/cli or vite. Ideally you should provide a runnable minimal reproducible example (on codesandbox.io or similar). Commented Sep 5, 2022 at 12:50

2 Answers 2

1

One solution is to export a type that adds findByTestId:

// my-vue-test-utils-plugin.ts
import { config, DOMWrapper, createWrapperError, type VueWrapper } from '@vue/test-utils'
               👇
export type TestWrapper = VueWrapper<any> & {
  findByTestId: (selector: string) => DOMWrapper<HTMLElement>
}

const DataTestIdPlugin = (wrapper: VueWrapper<any>) => {
  function findByTestId(selector: string) {
    const dataSelector = `[data-testid='${selector}']`
    const element = wrapper.element.querySelector(dataSelector)
    if (element) {
      return new DOMWrapper(element)
    }

    return createWrapperError('DOMWrapper')
  }

  return {
    findByTestId
  }
}

config.plugins.VueWrapper.install(DataTestIdPlugin as any)

Then, use type assertion (as keyword followed by the exported type above) on the mount() result:

// MyComponent.spec.ts
import type { TestWrapper } from './my-vue-test-utils-plugin.ts'

describe('MyComponent', () => {
  it('renders properly', () => {        👇
    const wrapper = mount(MyComponent) as TestWrapper
    expect(wrapper.findByTestId('my-component').text()).toBe('Hello World')
  })
})
Sign up to request clarification or add additional context in comments.

Comments

1

Another option is to create a .d.ts file e.g. vue-test-utils.d.ts with the following content:

import { DOMWrapper } from '@vue/test-utils';

declare module '@vue/test-utils' {
  export class VueWrapper {
    findByTestId(selector: string): DOMWrapper[];
  }
}

And include it in your tsconfig.json

  "include": [
     //...
     "./vue-test-utils.d.ts"
     //...
  ]

So you're able to extend the existing definition of the VueWrapper class.

1 Comment

This doesn't seem to work anymore after upgrading typescript, does this file need to be included somewhere? Edit: You need to add ` "paths": { "test-utils": ["./vue-test-utils.d.ts"] }` to compilerOptions of the tsconfig

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.