vuejs / test-utils

Vue Test Utils for Vue 3
https://test-utils.vuejs.org
MIT License
1.03k stars 245 forks source link

chore(index): exposing Stubs type for declaration files #2492

Closed joaoprp closed 1 month ago

joaoprp commented 1 month ago

Exposes Stubs over index.d.ts for ease of use on developers.

Being Stubs an existing type on test-utils, and having to import declarations on test files, this PR helps to remove boilerplate to always declare something along the lines of:

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

interface SetupProps {
  props: MyComponentProps;
  stubs: Record<string, boolean | typeof RouterLInkStub>;
}

function setup({ props = {}, stubs = {} }: SetupProps = {}) {
  render(MyComponent, {
    global: { stubs },
    props,
  });
}

test('something', () => {
  setup({ stubs: { 'router-link': RouterLinkStub, MyModal: true } });

  expect(screen.getByText('foo')).toBeDefined();
});

or setting up manually Component or DIrective types from vue itself:

import { RouterLinkStub } from '@vue/test-utils';
import { Component, Directive } from 'vue';

interface SetupProps {
  props: MyComponentProps;
  stubs: Record<string, boolean | Component | Directive>;
}

function setup({ props = {}, stubs = {} }: SetupProps = {}) {
  render(MyComponent, {
    global: { stubs },
    props,
  });
}

test('something', () => {
  setup({ stubs: { 'router-link': RouterLinkStub, MyModal: true } });

  expect(screen.getByText('foo')).toBeDefined();
});

In this second case, this Record<string, boolean | Component | Directive>, is basically what type Stubs is:

export type Stub = boolean | Component | Directive
export type Stubs = Record<string, Stub> | Array<string>

That could simplify the import boilerplate into:

import { RouterLinkStub, Stubs } from '@vue/test-utils';

interface SetupProps {
  props: MyComponentProps;
  stubs: Stubs;
}

function setup({ props = {}, stubs = {} }: SetupProps = {}) {
  render(MyComponent, {
    global: { stubs },
    props,
  });
}

test('something', () => {
  setup({ stubs: { 'router-link': RouterLinkStub, MyModal: true } });

  expect(screen.getByText('foo')).toBeDefined();
});

for a cleaner experience.

netlify[bot] commented 1 month ago

Deploy Preview for vue-test-utils-docs ready!

Name Link
Latest commit 51fa18a7f186785a65a4f32d8a0faf376d694880
Latest deploy log https://app.netlify.com/sites/vue-test-utils-docs/deploys/66bbe395fd9f9b0008551605
Deploy Preview https://deploy-preview-2492--vue-test-utils-docs.netlify.app
Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.