Git Product home page Git Product logo

testing-vue3's Introduction

⚠️ IMPORTANT NOTE:

Hey there! I wanted to thank you for using @storybook/testing-vue3!

@storybook/testing-vue3 has been promoted to a first-class Storybook functionality in Storybook 8. This means that you no longer need this package, and this package will not be worked on anymore. Instead, you can import the same utilities, but from the @storybook/vue3 package.

Please do the following:

  • Upgrade to Storybook 8 if you haven't already
  • Uninstall @storybook/testing-vue3
  • Update your imports from @storybook/testing-vue3 to @storybook/vue3
// Component.test.js
- import { composeStories } from '@storybook/testing-vue3';
+ import { composeStories } from '@storybook/vue3';

// setup-files.js
- import { setProjectAnnotations } from '@storybook/testing-vue3';
+ import { setProjectAnnotations } from '@storybook/vue3';

Please, if even after migrating, you are still experiencing issues, report them in the Storybook monorepo.

Thank you so much for this journey!


Storybook Testing Vue3

Testing utilities that allow you to reuse your Vue 3 stories in your unit tests


⚠️ This library is for Vue 3 projects. If you're using Storybook with Vue 2, please check @storybook/testing-vue instead!

Installation

This library should be installed as one of your project's devDependencies:

via npm

npm install --save-dev @storybook/testing-vue3

or via yarn

yarn add --dev @storybook/testing-vue3

Setup

Storybook CSF

This library requires you to be using Storybook's Component Story Format (CSF) and hoisted CSF annotations, which is the recommended way to write stories since Storybook 7.

Essentially, if your stories look similar to this, you're good to go!

// CSF: default export (meta) + named exports (stories)
export default {
  title: 'Example/Button',
  component: Button,
};

export const Primary = {
  template: '<Button v-bind="args" />',
};

Global config

This is an optional step. If you don't have global decorators, there's no need to do this. However, if you do, this is a necessary step for your global decorators to be applied.

If you have global decorators/parameters/etc and want them applied to your stories when testing them, you first need to set this up. You can do this by adding to or creating a jest setup file:

// setupFile.js <-- this will run before the tests in jest.
import { setProjectAnnotations } from '@storybook/testing-vue3';
import * as globalStorybookConfig from './.storybook/preview'; // path of your preview.js file

setProjectAnnotations(globalStorybookConfig);

For the setup file to be picked up, you need to pass it as an option to jest in your test command:

// package.json
{
  "test": "jest --setupFiles ./setupFile.js"
}

Usage

composeStories

composeStories will process all stories from the component you specify, compose args/decorators in all of them and return an object containing the composed stories.

If you use the composed story (e.g. PrimaryButton), the component will render with the args that are passed in the story. However, you are free to pass any props on top of the component, and those props will override the default values passed in the story's args.

import { render, screen } from '@testing-library/vue';
import { composeStories } from '@storybook/testing-vue3';
import * as stories from './Button.stories'; // import all stories from the stories file

// Every component that is returned maps 1:1 with the stories, but they already contain all decorators from story level, meta level and global level.
const { Primary, Secondary } = composeStories(stories);

test('renders primary button with default args', () => {
  render(Primary());
  const buttonElement = screen.getByText(
    /Text coming from args in stories file!/i
  );
  expect(buttonElement).not.toBeNull();
});

test('renders primary button with overriden props', () => {
  render(Secondary({ label: 'Hello world' })); // you can override props and they will get merged with values from the Story's args
  const buttonElement = screen.getByText(/Hello world/i);
  expect(buttonElement).not.toBeNull();
});

composeStory

You can use composeStory if you wish to apply it for a single story rather than all of your stories. You need to pass the meta (default export) as well.

import { render, screen } from '@testing-library/vue';
import { composeStory } from '@storybook/testing-vue3';
import Meta, { Primary as PrimaryStory } from './Button.stories';

// Returns a component that already contain all decorators from story level, meta level and global level.
const Primary = composeStory(PrimaryStory, Meta);

test('onclick handler is called', async () => {
  const onClickSpy = jest.fn();
  render(Primary({ onClick: onClickSpy }));
  const buttonElement = screen.getByRole('button');
  buttonElement.click();
  expect(onClickSpy).toHaveBeenCalled();
});

License

MIT

testing-vue3's People

Contributors

almaraubel avatar chakas3 avatar elevatebart avatar i-udas avatar yannbf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

testing-vue3's Issues

Support story format CSF v3.0

I'm write the stories with new CSF v3.0 format, but testing-vue3 support only the previous CSF format. When will available the support to the new format?

Component example:

export default {
  title: "Components/Button",
  component: Button
} as Meta;

export const Basic: Story = {
  parameters: {
    docs: {
      source: {
        code: `<Button>Example</Button>`
      },
      description: {
        component: "Customizable button with content."
      }
    }
  }
};

I get this error, when trying to use CSF 3.0 stories with composeStories.

 packages/components/src/button/Button.test.ts [ packages/components/src/button/Button.test.ts ]
Error: Cannot compose story due to invalid format. @storybook/testing-vue expected a function but received object instead.
 ❯ composeStory node_modules/.pnpm/@[email protected]_i2pafdhxvhztb374fr7cj3wsfq/node_modules/@storybook/testing-vue3/dist/testing-vue3.cjs.development.js:140:11
 ❯ node_modules/.pnpm/@[email protected]_i2pafdhxvhztb374fr7cj3wsfq/node_modules/@storybook/testing-vue3/dist/testing-vue3.cjs.development.js:194:23
 ❯ Proxy.composeStories node_modules/.pnpm/@[email protected]_i2pafdhxvhztb374fr7cj3wsfq/node_modules/@storybook/testing-vue3/dist/testing-vue3.cjs.development.js:191:49
 ❯ packages/components/src/button/Button.test.ts:8:18
      6| import { Button } from "./index";
      7| 
      8| const { Basic } = composeStories(stories);
       |                  ^
      9| 
     10| describe("Basic tests", () => {

Environment

  • OS: MacOS
  • Node.js version: v16.13.2
  • NPM version: 8.1.2

Additional context

{ ...
"@storybook/vue3": "^6.5.9",
"@storybook/testing-vue3": "^0.0.2",
"@storybook/builder-vite": "^0.2.0",
"@testing-library/vue": "^6.6.1",
"vitest": "^0.18.1",
...
}

[Bug] Issue with composeStories when used with Vitest in Storybook 7

Describe the bug

I've been starting to migrate our Vite/Vue 3 repo over to Storybook 7 and I'm running into a weird error as soon as I import composeStories into a test file.

Simply by adding the following lines:

import * as stories from './BasicButton.stories.js'
import { composeStories } from '@storybook/testing-vue3'
const composed = composeStories(stories)

I get the following error:

 FAIL  src/components/BasicButton/BasicButton.spec.ts [ src/components/BasicButton/BasicButton.spec.ts ]
TypeError: addons__default.setChannel is not a function
 ❯ Object.<anonymous> node_modules/@storybook/testing-vue3/src/index.ts:11:8
 ❯ Object.<anonymous> node_modules/@storybook/testing-vue3/dist/index.js:7:20

Which seems to be happening here. I have @storybook/addons installed, but I assume it might be expecting an instance of Storybook that wouldn't be running when we're doing unit tests outside of Storybook?

Steps to reproduce the behavior

  1. I've created a sample repo here: https://github.com/K3TH3R/composeStories-issue-storybook-7
  2. If you clone/install and then run yarn test:unit, you should see the error.
  3. If you comment out this line you should see the test finish as expected.

Expected behavior

I would expect to be able to run this properly. This exact setup is working as expected when we're on Storybook v6.

Environment

  • OS: Mac OS
  • Node.js version: 16.19.0
  • NPM version: 8.19.3

composeStories() ignores excludeStories

If you have a named Export in a CSF Story, tests will fail, even if it is excluded with excludeStories: /.*Props$/:

export const PrimaryProps: ButtonType = {
  size: 'medium',
  variant: 'primary',
  text: 'my happy primary button',
}
export const Primary = Template.bind({})
Primary.args = PrimaryProps

Error: Cannot compose story due to invalid format. @storybook/testing-vue expected a function but received object instead.

https://storybook.js.org/docs/react/api/csf#non-story-exports

This package is deprecated as it is a core functionality of Storybook 8!

Hey there! I wanted to thank you for using @storybook/testing-vue3!

@storybook/testing-vue3 has been promoted to a first-class Storybook functionality in Storybook 8. This means that you no longer need this package, and this package will not be worked on anymore (especially regarding Storybook 7, unless there are security issues). Instead, you can import the same utilities, but from the @storybook/vue3 package.

Please do the following:

Upgrade to Storybook 8 if you haven't already
Uninstall @storybook/testing-vue3
Update your imports from @storybook/testing-vue3 to @storybook/vue3

// Component.test.js
- import { composeStories } from '@storybook/testing-vue3';
+ import { composeStories } from '@storybook/vue3';

// setup-files.js
- import { setProjectAnnotations } from '@storybook/testing-vue3';
+ import { setProjectAnnotations } from '@storybook/vue3';

Please, if even after migrating, you are still experiencing issues, report them in the Storybook monorepo.

Thank you so much for this journey!

Components not rendering in Cypress

testing-vue3 doesnt seem to work with cypress (9.0.0). The component simply doesnt render.

import CrashTestDummy from '@/components/CrashTestDummy/CrashTestDummy.vue';
const { Primary, Secondary } = composeStories(stories);

// does not work
mount(Primary, componentConfig);

// works, widget renders fine.
mount(CrashTestDummy, componentConfig);

CrashTestDummy.vue is just an empty component with some dummy text.

TypeError: Cannot read properties of undefined (reading 'addEventListener')

Because this error occurred during a `before each` hook we are skipping the remaining tests in the current suite: `Test if locale works in Cyp...`
    at _loop_1 (http://localhost:3000/__cypress/src/node_modules/.vite/@cypress_vue.js?v=f1d54d89:6013:15)
    at VueWrapper2.attachNativeEventListener (http://localhost:3000/__cypress/src/node_modules/.vite/@cypress_vue.js?v=f1d54d89:6023:7)
    at new VueWrapper2 (http://localhost:3000/__cypress/src/node_modules/.vite/@cypress_vue.js?v=f1d54d89:5986:11)
    at createWrapper (http://localhost:3000/__cypress/src/node_modules/.vite/@cypress_vue.js?v=f1d54d89:6137:10)
    at mount (http://localhost:3000/__cypress/src/node_modules/.vite/@cypress_vue.js?v=f1d54d89:6337:17)
    at Context.<anonymous> (http://localhost:3000/__cypress/src/node_modules/.vite/@cypress_vue.js?v=f1d54d89:6513:19)
    at getRet (http://localhost:3000/__cypress/runner/cypress_runner.js:172283:20)
From previous event:
    at Context.thenFn (http://localhost:3000/__cypress/runner/cypress_runner.js:172301:63)
    at Context.then (http://localhost:3000/__cypress/runner/cypress_runner.js:172753:21)
    at Context.<anonymous> (http://localhost:3000/__cypress/runner/cypress_runner.js:189216:23)
    at http://localhost:3000/__cypress/runner/cypress_runner.js:187816:17
From previous event:
    at runCommand (http://localhost:3000/__cypress/runner/cypress_runner.js:187795:10)
    at next (http://localhost:3000/__cypress/runner/cypress_runner.js:187936:16)
From previous event:
    at http://localhost:3000/__cypress/runner/cypress_runner.js:202259:79
From previous event:
    at Object.run (http://localhost:3000/__cypress/runner/cypress_runner.js:202254:23)
    at Object.run (http://localhost:3000/__cypress/runner/cypress_runner.js:187991:17)
    at $Cy.cy.<computed> [as then] (http://localhost:3000/__cypress/runner/cypress_runner.js:189256:19)
    at mount2 (http://localhost:3000/__cypress/src/node_modules/.vite/@cypress_vue.js?v=f1d54d89:6491:13)
    at Context.<anonymous> (http://localhost:3000/src/components/CrashTestDummy/CrashTestDummy.spec.ts?import:23:5)
    at Context.runnable.fn (http://localhost:3000/__cypress/runner/cypress_runner.js:189471:23)
    at callFn (http://localhost:3000/__cypress/runner/cypress_runner.js:142125:21)
    at Hook.../driver/node_modules/mocha/lib/runnable.js.Runnable.run (http://localhost:3000/__cypress/runner/cypress_runner.js:142112:7)
    at http://localhost:3000/__cypress/runner/cypress_runner.js:196060:30
From previous event:
    at Object.onRunnableRun (http://localhost:3000/__cypress/runner/cypress_runner.js:196045:19)
    at $Cypress.action (http://localhost:3000/__cypress/runner/cypress_runner.js:185468:28)
    at Hook.Runnable.run (http://localhost:3000/__cypress/runner/cypress_runner.js:193741:13)
    at next (http://localhost:3000/__cypress/runner/cypress_runner.js:142627:10)
    at http://localhost:3000/__cypress/runner/cypress_runner.js:142671:5
    at timeslice (http://localhost:3000/__cypress/runner/cypress_runner.js:136597:27)
logError @ cypress_runner.js:210452
(anonymous) @ cypress_runner.js:208862
emit @ cypress_runner.js:83077
(anonymous) @ cypress_runner.js:205507
emit @ cypress_runner.js:83077
emit @ cypress_runner.js:205568
onPrint @ cypress_runner.js:204397
_onPrintClick @ cypress_runner.js:204402
(anonymous) @ cypress_runner.js:205739
executeAction @ cypress_runner.js:80835
n @ cypress_runner.js:80835
ca @ cypress_runner.js:91425
ja @ cypress_runner.js:91426
ka @ cypress_runner.js:91426
wa @ cypress_runner.js:91428
Aa @ cypress_runner.js:91429
ya @ cypress_runner.js:91429
Da @ cypress_runner.js:91432
Ad @ cypress_runner.js:91495
Gi @ cypress_runner.js:91661
Kb @ cypress_runner.js:91450
Dd @ cypress_runner.js:91497
(anonymous) @ cypress_runner.js:91662
../../node_modules/scheduler/cjs/scheduler.production.min.js.exports.unstable_runWithPriority @ cypress_runner.js:99528
Ii @ cypress_runner.js:91662
Cd @ cypress_runner.js:91496

Using Play inside test files

I noticed there isn't an option to run interactions from within a test file with the Play method. I have it running on a forked branch, but can't get it to actually execute userEvents. Is there any proposed update with this feature on the roadmap? I noticed it on the React version.

[Question/Bug]Assert Event has been emitted

Describe the bug

Is it possible to assert that a certain event was emitted from the component which was included in the story?

Steps to reproduce the behavior

When I test a component withou storybook/testing-vue3 i could assert that an certain event has been emitted.

This is working

test('When Postcode of Huisnummer is made empty again Should emit empty event', async () => {
    const user = userEvent.setup();
    const {getByPlaceholderText, emitted}= render(AdresField, { });
    const placeField = getByPlaceholderText('Place');
    await user.type(placeField , 'Alkmaar');
    await user.keyboard('[Tab]'); 
    expect(emitted<{ value: Adres }[]>().updateField.length).toEqual(1);
  });

When using compose story i could not assert that an specific event was emitted. I think this has some thing to do with the story which already handles the emitted @updateField event. Is there a way to pass this event to the unit test?
adres.spec.ts

const { Default} = composeStories(stories);
test('When Postcode of Huisnummer is made empty again Should emit empty event', async () => {
    const user = userEvent.setup();
    const {getByPlaceholderText, emitted}= render(Default());
    const placeField = getByPlaceholderText('Place');
    await user.type(placeField , 'Alkmaar');
    await user.keyboard('[Tab]'); 
    expect(emitted<{ value: Adres }[]>().updateField.length).toEqual(1);
  });

adres.stories.ts

const Template: Story<AdresFieldType> = (args: AdresFieldType) => ({
  components: { AdresField },
  setup() {
    return { args, onChange: action('Value changed') };
  },
  template: '<AdresField v-bind="args" @updateField="onChange"/>'
});

export const Default = Template.bind({});
Default.args = {
  path: 'v1929',
  value: {
    huisnummer: 193,
    postcode: '1822 PA'
  },
  lookup: lookupMock
};

Storybook 7.6 is not supported

Describe the bug
The 7.6 update and more specifically this MR broke the package. The ./preview entry point used by this package has been removed and so now the following error is thrown when including it:

Error: Package subpath './preview' is not defined by "exports" in /node_modules/@storybook/vue3/package.json
 ❯ Object.<anonymous> node_modules/@storybook/testing-vue3/dist/testing-vue3.cjs.development.js:7:33

I'm using the following setup:

    "@storybook/addon-essentials": "^7.6.0",
    "@storybook/addon-interactions": "^7.6.0",
    "@storybook/addon-links": "^7.6.0",
    "@storybook/blocks": "^7.6.0",
    "@storybook/testing-vue3": "^1.0.0",
    "@storybook/vue3": "^7.6.0",
    "@storybook/vue3-vite": "^7.6.0",
    ...
    "storybook": "^7.6.0",
    "typescript": "^5.3.2",
    "vite": "^5.0.2",
    "vitest": "^0.34.6",

To Reproduce
Do a test with Storybook 7.6 including the package and run it

Expected behavior
I'm guessing the import should be updated.

Additional context
More of an additional question, the release log mention that you'd like to put the functionality of this package in @storybook/vue3. Do you have any updates on this? I feel like it would have helped avoiding that issue.

[Bug] not loading global directives

Describe the bug

Adding a global directive to the 'preview.js' file is not available for the component when rendering.

Steps to reproduce the behavior

Add the following into preview.js and add to setup via setGlobalConfig.

import { app } from '@storybook/vue3';

app.directive('directive', directive);

Expected behavior

I would expect the directive to be available in the component for rendering.

Screenshots and/or logs

TypeError: Cannot read property 'deep' of undefined
 ❯ Module.withDirectives node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:2754:17
 ❯ Proxy.render src/components/jobs/job-list-item.vue?vue&type=template&lang.js:69:35
 ❯ renderComponentRoot node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:890:44
 ❯ ReactiveEffect.componentUpdateFn [as fn] node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5503:57
 ❯ ReactiveEffect.run node_modules/@vue/reactivity/dist/reactivity.cjs.js:189:25
 ❯ instance.update node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5617:56
 ❯ setupRenderEffect node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5631:9
 ❯ mountComponent node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5413:9
 ❯ processComponent node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5371:17
 ❯ patch node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4973:21

Environment

  • OS: MacOS 12.3.1
  • Node.js version: v14.19.1
  • Yarn version: 1.22.10

Add support for storybook 7

No next version seems to have been created for this library, which breaks our whole test suite when attempting to upgrade to storybook 7

I've had a look at the issue a little bit, and after updating addons to use a named export (#9) there is a bunch of typing changes that I can't quite figure out.

This has been done for the react equivalent repo already here storybookjs/testing-react#120 and a lot of it would be re-usable here as far as I can tell

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.