Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test: Add mount property to the story context #28383

Merged
merged 38 commits into from
Jul 3, 2024
Merged

Test: Add mount property to the story context #28383

merged 38 commits into from
Jul 3, 2024

Conversation

kasperpeulen
Copy link
Contributor

@kasperpeulen kasperpeulen commented Jun 28, 2024

What I did

This PR implements most of the following RFC:
[RFC] Allow play to mount the component of the story

The idea is simply that you can do something after and before mounting in the play function:

export const MountInPlay = {
beforeEach() {
console.log('3 - [from story beforeEach]');
},
decorators: (storyFn) => {
console.log('5 - [from decorator]');
return storyFn();
},
args: {
label: 'Button',
onClick: () => {
console.log('7 - [from onClick]');
},
},
async play({ mount, canvasElement }) {
console.log('4 - [before mount]');
await mount();
console.log('6 - [after mount]');
await userEvent.click(getByRole(canvasElement, 'button'));
await expect(mocked(console.log).mock.calls).toEqual([
['1 - [from loaders]'],
['2 - [from meta beforeEach]'],
['3 - [from story beforeEach]'],
['4 - [before mount]'],
['5 - [from decorator]'],
['6 - [after mount]'],
['7 - [from onClick]'],
]);
},
};

To make this a non-breaking change, we need to know if mount is used inside of the play function.

We implemented for this, something similar as playwright/vitest fixtures. We analyze the "deps" of the play function by looking at what properties of the context are destructured. If you use mount without destructuring you get an error:

const mountDestructured = playFunction && getUsedProps(playFunction).includes('mount');
if (!mounted && !mountDestructured) {
await context.mount();
}
this.notYetRendered = false;
if (abortSignal.aborted) return;
const ignoreUnhandledErrors =
this.story.parameters?.test?.dangerouslyIgnoreUnhandledErrors === true;
const unhandledErrors: Set<unknown> = new Set();
const onError = (event: ErrorEvent | PromiseRejectionEvent) =>
unhandledErrors.add('error' in event ? event.error : event.reason);
// The phase should be 'rendering' but it might be set to 'aborted' by another render cycle
if (this.renderOptions.autoplay && forceRemount && playFunction && this.phase !== 'errored') {
window.addEventListener('error', onError);
window.addEventListener('unhandledrejection', onError);
this.disableKeyListeners = true;
try {
if (!mountDestructured) {
context.mount = async () => {
throw new MountMustBeDestructured({ playFunction: playFunction.toString() });
};
}
await this.runPhase(abortSignal, 'playing', async () => {
await playFunction(context);
});

Portable stories

For portable stories, we introduce a Story.play which plays the whole story, including cleanup, loaders, beforeEach, render and play. It can be called like this:

it('renders with play function without canvas element', async () => {
const CSF3InputFieldFilled = composeStory(stories.CSF3InputFieldFilled, stories.default);
await CSF3InputFieldFilled.play();
const input = screen.getByTestId('input') as HTMLInputElement;
expect(input.value).toEqual('Hello world!');
});

Checklist for Contributors

Testing

The changes in this PR are covered in the following automated tests:

  • stories
  • unit tests
  • integration tests
  • end-to-end tests

Manual testing

This section is mandatory for all contributions. If you believe no manual test is necessary, please state so explicitly. Thanks!

Documentation

  • Add or update documentation reflecting your changes
  • If you are deprecating/removing a feature, make sure to update
    MIGRATION.MD

Checklist for Maintainers

  • When this PR is ready for testing, make sure to add ci:normal, ci:merged or ci:daily GH label to it to run a specific set of sandboxes. The particular set of sandboxes can be found in code/lib/cli/src/sandbox-templates.ts

  • Make sure this PR contains one of the labels below:

    Available labels
    • bug: Internal changes that fixes incorrect behavior.
    • maintenance: User-facing maintenance tasks.
    • dependencies: Upgrading (sometimes downgrading) dependencies.
    • build: Internal-facing build tooling & test updates. Will not show up in release changelog.
    • cleanup: Minor cleanup style change. Will not show up in release changelog.
    • documentation: Documentation only changes. Will not show up in release changelog.
    • feature request: Introducing a new feature.
    • BREAKING CHANGE: Changes that break compatibility in some way with current major version.
    • other: Changes that don't fit in the above categories.

🦋 Canary release

This PR does not have a canary release associated. You can request a canary release of this pull request by mentioning the @storybookjs/core team here.

core team members can create a canary release here or locally with gh workflow run --repo storybookjs/storybook canary-release-pr.yml --field pr=<PR_NUMBER>

@kasperpeulen kasperpeulen changed the base branch from next to kasper/canvas June 28, 2024 12:14
Copy link

nx-cloud bot commented Jun 28, 2024

☁️ Nx Cloud Report

CI is running/has finished running commands for commit 9678d6f. As they complete they will appear below. Click to see the status, the terminal output, and the build insights.

📂 See all runs for this CI Pipeline Execution


✅ Successfully ran 1 target

Sent with 💌 from NxCloud.

@kasperpeulen kasperpeulen marked this pull request as ready for review June 28, 2024 14:22
Copy link
Member

@tmeasday tmeasday left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In general I think the approach is good, but it's definitely missing tests, which I think would help understand what it is doing.

code/lib/core-events/src/errors/preview-errors.ts Outdated Show resolved Hide resolved
code/lib/preview-api/src/modules/preview-web/Preview.tsx Outdated Show resolved Hide resolved
Comment on lines 197 to 201
await this.runPhase(abortSignal, 'rendering', async () => {
const teardown = await this.renderToScreen(renderContext, canvasElement);
this.teardownRender = teardown || (() => {});
mounted = true;
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand why the runPhase code is up here, it seems like the wrong place? Shouldn't just be down on line 245, in flow with the rest of it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason is that this is also called when calling mount from inside the play function and line 245 is only called, when mount is not used.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, I see. I guess this control flow from StoryRender -> story.mount (in prepareStory) -> renderToCanvas, or StoryRender -> play -> context.mount -> renderToCanvas is pretty hard to understand off the bat.

Is there something we can do to make it easier to follow (either in code or just comments?)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will refactor this bit in a new PR.

Comment on lines 117 to 118
// Play is not supported in docs yet, and when mount is used, the mounting is happening in play itself.
tags = tags.filter((tag) => tag !== 'autodocs');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does this do exactly?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to improve the message.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// Don't show stories where mount is used in docs.
// As the play function is not running in docs, and when mount is used, the mounting is happening in play itself.

Copy link
Member

@tmeasday tmeasday Jul 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe:

// Hide stories that mount inside the `play` function from docs
// Docs doesn't currently run the `play` function, so such stories would never be mounted.

This does seem like the sort of thing that will confuse users though ("why has my story disappeared from docs?"). I wonder if there's some way we could make it more obvious for folks.

Also I wonder if we should alter the tag in the index rather than dynamically here. WDYT @shilman?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Working on a new PR that fixes this

code/lib/preview-api/src/modules/store/csf/prepareStory.ts Outdated Show resolved Hide resolved
code/lib/preview-api/src/modules/store/csf/prepareStory.ts Outdated Show resolved Hide resolved
code/lib/preview-api/src/modules/store/csf/prepareStory.ts Outdated Show resolved Hide resolved
const teardown = await this.renderToScreen(renderContext, canvasElement);
this.teardownRender = teardown || (() => {});
});
const isMountDestructured = playFunction && mountDestructured(playFunction);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should store this property on the prepared story rather than checking in multiple places?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am working on a new PR that fixes this.

Base automatically changed from kasper/canvas to next July 2, 2024 11:16
const mountUsed = mountDestructured(playFunction);

if (!render && !mountUsed) {
// TODO Make this a named error
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reminder to accommodate this TODO in a followup PR or this one if you prefer

@kasperpeulen kasperpeulen merged commit 137c344 into next Jul 3, 2024
52 of 54 checks passed
@kasperpeulen kasperpeulen deleted the kasper/mount branch July 3, 2024 08:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants