Adjust tests for Vitest 3

This commit is contained in:
Valentin Palkovic 2025-01-03 11:53:19 +01:00
parent 09196b1fe7
commit e61762b41a
9 changed files with 132 additions and 134 deletions

View File

@ -104,122 +104,118 @@ beforeEach(() => {
* Skipping this test, because it causes a cyclical dependency error, where core depends on docs & * Skipping this test, because it causes a cyclical dependency error, where core depends on docs &
* blocks This was done to avoid a conflict in the CPC work, we should revisit this. * blocks This was done to avoid a conflict in the CPC work, we should revisit this.
*/ */
describe.skip( describe('PreviewWeb', { skip: true }, () => {
'PreviewWeb', describe('initial render', () => {
() => { it('renders story mode through the stack', async () => {
describe('initial render', () => { const { DocsRenderer } = await import('../../../../../addons/docs/src/index');
it('renders story mode through the stack', async () => { projectAnnotations.parameters.docs.renderer = () => new DocsRenderer() as any;
const { DocsRenderer } = await import('../../../../../addons/docs/src/index');
projectAnnotations.parameters.docs.renderer = () => new DocsRenderer() as any;
projectAnnotations.renderToCanvas.mockImplementationOnce( projectAnnotations.renderToCanvas.mockImplementationOnce(({ storyFn }: RenderContext<any>) =>
({ storyFn }: RenderContext<any>) => storyFn() storyFn()
); );
document.location.search = '?id=component-one--a'; document.location.search = '?id=component-one--a';
await new PreviewWeb(importFn, getProjectAnnotations).ready(); await new PreviewWeb(importFn, getProjectAnnotations).ready();
await waitForRender(); await waitForRender();
await vi.waitFor(() => { await vi.waitFor(() => {
expect(projectAnnotations.decorators[0]).toHaveBeenCalled(); expect(projectAnnotations.decorators[0]).toHaveBeenCalled();
expect(projectAnnotations.render).toHaveBeenCalled(); expect(projectAnnotations.render).toHaveBeenCalled();
});
});
it('renders docs mode through docs page', async () => {
const { DocsRenderer } = await import('../../../../../addons/docs/src/index');
projectAnnotations.parameters.docs.renderer = () => new DocsRenderer() as any;
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = new PreviewWeb(importFn, getProjectAnnotations);
const docsRoot = document.createElement('div');
vi.mocked(preview.view.prepareForDocs).mockReturnValue(docsRoot as any);
componentOneExports.default.parameters.docs.container.mockImplementationOnce(() =>
React.createElement('div', {}, 'INSIDE')
);
await preview.ready();
await vi.waitFor(
() => {
if (docsRoot.outerHTML !== '<div><div>INSIDE</div></div>') {
throw new Error('DocsRoot not ready yet');
}
},
{
timeout: 2000,
}
);
expect(docsRoot.outerHTML).toMatchInlineSnapshot('"<div><div>INSIDE</div></div>"');
// Extended timeout to try and avoid
// Error: Event was not emitted in time: storyRendered,docsRendered,storyThrewException,storyErrored,storyMissing
}, 10_000);
it('sends docs rendering exceptions to showException', async () => {
const { DocsRenderer } = await import('../../../../../addons/docs/src/index');
projectAnnotations.parameters.docs.renderer = () => new DocsRenderer() as any;
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = new PreviewWeb(importFn, getProjectAnnotations);
const docsRoot = document.createElement('div');
vi.mocked(preview.view.prepareForDocs).mockReturnValue(docsRoot as any);
componentOneExports.default.parameters.docs.container.mockImplementation(() => {
throw new Error('Docs rendering error');
});
vi.mocked(preview.view.showErrorDisplay).mockClear();
await preview.ready();
await vi.waitFor(
() => {
expect(preview.view.showErrorDisplay).toHaveBeenCalled();
},
{
timeout: 2000,
}
);
}); });
}); });
describe('onGetGlobalMeta changed (HMR)', () => { it('renders docs mode through docs page', async () => {
const newGlobalDecorator = vi.fn((s) => s()); const { DocsRenderer } = await import('../../../../../addons/docs/src/index');
const newGetProjectAnnotations = () => { projectAnnotations.parameters.docs.renderer = () => new DocsRenderer() as any;
return {
...projectAnnotations, document.location.search = '?id=component-one--docs&viewMode=docs';
args: { a: 'second' }, const preview = new PreviewWeb(importFn, getProjectAnnotations);
globals: { a: 'second' },
decorators: [newGlobalDecorator], const docsRoot = document.createElement('div');
}; vi.mocked(preview.view.prepareForDocs).mockReturnValue(docsRoot as any);
componentOneExports.default.parameters.docs.container.mockImplementationOnce(() =>
React.createElement('div', {}, 'INSIDE')
);
await preview.ready();
await vi.waitFor(
() => {
if (docsRoot.outerHTML !== '<div><div>INSIDE</div></div>') {
throw new Error('DocsRoot not ready yet');
}
},
{
timeout: 2000,
}
);
expect(docsRoot.outerHTML).toMatchInlineSnapshot('"<div><div>INSIDE</div></div>"');
// Extended timeout to try and avoid
// Error: Event was not emitted in time: storyRendered,docsRendered,storyThrewException,storyErrored,storyMissing
}, 10_000);
it('sends docs rendering exceptions to showException', async () => {
const { DocsRenderer } = await import('../../../../../addons/docs/src/index');
projectAnnotations.parameters.docs.renderer = () => new DocsRenderer() as any;
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = new PreviewWeb(importFn, getProjectAnnotations);
const docsRoot = document.createElement('div');
vi.mocked(preview.view.prepareForDocs).mockReturnValue(docsRoot as any);
componentOneExports.default.parameters.docs.container.mockImplementation(() => {
throw new Error('Docs rendering error');
});
vi.mocked(preview.view.showErrorDisplay).mockClear();
await preview.ready();
await vi.waitFor(
() => {
expect(preview.view.showErrorDisplay).toHaveBeenCalled();
},
{
timeout: 2000,
}
);
});
});
describe('onGetGlobalMeta changed (HMR)', () => {
const newGlobalDecorator = vi.fn((s) => s());
const newGetProjectAnnotations = () => {
return {
...projectAnnotations,
args: { a: 'second' },
globals: { a: 'second' },
decorators: [newGlobalDecorator],
}; };
};
it('renders story mode through the updated stack', async () => { it('renders story mode through the updated stack', async () => {
const { DocsRenderer } = await import('../../../../../addons/docs/src/index'); const { DocsRenderer } = await import('../../../../../addons/docs/src/index');
projectAnnotations.parameters.docs.renderer = () => new DocsRenderer() as any; projectAnnotations.parameters.docs.renderer = () => new DocsRenderer() as any;
document.location.search = '?id=component-one--a'; document.location.search = '?id=component-one--a';
const preview = new PreviewWeb(importFn, getProjectAnnotations); const preview = new PreviewWeb(importFn, getProjectAnnotations);
await preview.ready(); await preview.ready();
await waitForRender(); await waitForRender();
projectAnnotations.renderToCanvas.mockImplementationOnce( projectAnnotations.renderToCanvas.mockImplementationOnce(({ storyFn }: RenderContext<any>) =>
({ storyFn }: RenderContext<any>) => storyFn() storyFn()
); );
projectAnnotations.decorators[0].mockClear(); projectAnnotations.decorators[0].mockClear();
mockChannel.emit.mockClear(); mockChannel.emit.mockClear();
preview.onGetProjectAnnotationsChanged({ getProjectAnnotations: newGetProjectAnnotations }); preview.onGetProjectAnnotationsChanged({ getProjectAnnotations: newGetProjectAnnotations });
await vi.waitFor(() => { await vi.waitFor(() => {
expect(projectAnnotations.decorators[0]).not.toHaveBeenCalled(); expect(projectAnnotations.decorators[0]).not.toHaveBeenCalled();
expect(newGlobalDecorator).toHaveBeenCalled(); expect(newGlobalDecorator).toHaveBeenCalled();
expect(projectAnnotations.render).toHaveBeenCalled(); expect(projectAnnotations.render).toHaveBeenCalled();
});
}); });
}); });
}, });
{ retry: 0 } });
);

View File

@ -18,20 +18,20 @@ describe('angular component properties', () => {
expect(true).toEqual(true); expect(true).toEqual(true);
}); });
// TODO: Fix this test // TODO: Fix this test
// it(`${testEntry.name}`, () => { // it(`${testEntry.name}`, async () => {
// const inputPath = join(testDir, testFile); // const inputPath = join(testDir, testFile);
// // snapshot the output of compodoc // // snapshot the output of compodoc
// const compodocOutput = runCompodoc(inputPath); // const compodocOutput = runCompodoc(inputPath);
// const compodocJson = JSON.parse(compodocOutput); // const compodocJson = JSON.parse(compodocOutput);
// expect(compodocJson).toMatchFileSnapshot( // await expect(compodocJson).toMatchFileSnapshot(
// join(testDir, `compodoc-${SNAPSHOT_OS}.snapshot`) // join(testDir, `compodoc-${SNAPSHOT_OS}.snapshot`)
// ); // );
// // snapshot the output of addon-docs angular-properties // // snapshot the output of addon-docs angular-properties
// const componentData = findComponentByName('InputComponent', compodocJson); // const componentData = findComponentByName('InputComponent', compodocJson);
// const argTypes = extractArgTypesFromData(componentData); // const argTypes = extractArgTypesFromData(componentData);
// expect(argTypes).toMatchFileSnapshot(join(testDir, 'argtypes.snapshot')); // await expect(argTypes).toMatchFileSnapshot(join(testDir, 'argtypes.snapshot'));
// }); // });
} }
} }

View File

@ -24,8 +24,8 @@ readdirSync(fixturesDir).forEach((transformName) => {
.filter((fileName) => inputRegExp.test(fileName)) .filter((fileName) => inputRegExp.test(fileName))
.forEach((fileName) => { .forEach((fileName) => {
const inputPath = join(transformFixturesDir, fileName); const inputPath = join(transformFixturesDir, fileName);
it(`transforms correctly using "${fileName}" data`, () => it(`transforms correctly using "${fileName}" data`, async () =>
expect( await expect(
applyTransform(require(join(__dirname, '..', transformName)), null, { applyTransform(require(join(__dirname, '..', transformName)), null, {
path: inputPath, path: inputPath,
source: fs.readFileSync(inputPath, 'utf8'), source: fs.readFileSync(inputPath, 'utf8'),

View File

@ -25,7 +25,7 @@ async function generate(filePath: string) {
it(`${fixtureFile}`, async () => { it(`${fixtureFile}`, async () => {
const inputPath = join(transformFixturesDir, fixtureFile); const inputPath = join(transformFixturesDir, fixtureFile);
const code = await generate(inputPath); const code = await generate(inputPath);
expect(code).toMatchFileSnapshot(inputPath.replace(inputRegExp, '.snapshot')); await expect(code).toMatchFileSnapshot(inputPath.replace(inputRegExp, '.snapshot'));
}); });
}); });
}); });

View File

@ -77,8 +77,8 @@ describe('renders', () => {
expect(screen.getByTestId('loaded-data').textContent).toEqual('loaded data'); expect(screen.getByTestId('loaded-data').textContent).toEqual('loaded data');
}); });
it('should throw an error in play function', () => { it('should throw an error in play function', async () => {
expect(() => MountInPlayFunctionThrow.run()).rejects.toThrowError('Error thrown in play'); await expect(() => MountInPlayFunctionThrow.run()).rejects.toThrowError('Error thrown in play');
}); });
it('should call and compose loaders data', async () => { it('should call and compose loaders data', async () => {

View File

@ -71,12 +71,12 @@ describe('react component properties', () => {
if (skippedTests.includes(testEntry.name)) { if (skippedTests.includes(testEntry.name)) {
it.skip(`${testEntry.name}`, () => {}); it.skip(`${testEntry.name}`, () => {});
} else { } else {
it(`${testEntry.name}`, () => { it(`${testEntry.name}`, async () => {
const inputPath = join(testDir, testFile); const inputPath = join(testDir, testFile);
// snapshot the output of babel-plugin-react-docgen // snapshot the output of babel-plugin-react-docgen
const docgenPretty = annotateWithDocgen(inputPath); const docgenPretty = annotateWithDocgen(inputPath);
expect(docgenPretty).toMatchFileSnapshot(join(testDir, 'docgen.snapshot')); await expect(docgenPretty).toMatchFileSnapshot(join(testDir, 'docgen.snapshot'));
// transform into an uglier format that's works with require-from-string // transform into an uglier format that's works with require-from-string
const docgenModule = transformToModule(docgenPretty); const docgenModule = transformToModule(docgenPretty);
@ -84,7 +84,7 @@ describe('react component properties', () => {
// snapshot the output of component-properties/react // snapshot the output of component-properties/react
const { component } = requireFromString(docgenModule, inputPath); const { component } = requireFromString(docgenModule, inputPath);
const properties = extractProps(component); const properties = extractProps(component);
expect(properties).toMatchFileSnapshot(join(testDir, 'properties.snapshot')); await expect(properties).toMatchFileSnapshot(join(testDir, 'properties.snapshot'));
// snapshot the output of `extractArgTypes` // snapshot the output of `extractArgTypes`
const argTypes = extractArgTypes(component); const argTypes = extractArgTypes(component);
@ -93,7 +93,7 @@ describe('react component properties', () => {
argTypes, argTypes,
parameters, parameters,
} as unknown as StoryContext<Renderer>); } as unknown as StoryContext<Renderer>);
expect(rows).toMatchFileSnapshot(join(testDir, 'argTypes.snapshot')); await expect(rows).toMatchFileSnapshot(join(testDir, 'argTypes.snapshot'));
}); });
} }
} }

View File

@ -46,7 +46,7 @@ describe('web-components component properties', () => {
const testDir = join(fixturesDir, testEntry.name); const testDir = join(fixturesDir, testEntry.name);
const testFile = readdirSync(testDir).find((fileName) => inputRegExp.test(fileName)); const testFile = readdirSync(testDir).find((fileName) => inputRegExp.test(fileName));
if (testFile) { if (testFile) {
it(`${testEntry.name}`, () => { it(`${testEntry.name}`, async () => {
const inputPath = join(testDir, testFile); const inputPath = join(testDir, testFile);
// snapshot the output of wca // snapshot the output of wca
@ -55,11 +55,13 @@ describe('web-components component properties', () => {
customElements.tags.forEach((tag: any) => { customElements.tags.forEach((tag: any) => {
tag.path = 'dummy-path-to-component'; tag.path = 'dummy-path-to-component';
}); });
expect(customElements).toMatchFileSnapshot(join(testDir, 'custom-elements.snapshot')); await expect(customElements).toMatchFileSnapshot(
join(testDir, 'custom-elements.snapshot')
);
// snapshot the properties // snapshot the properties
const properties = extractArgTypesFromElements('input', customElements); const properties = extractArgTypesFromElements('input', customElements);
expect(properties).toMatchFileSnapshot(join(testDir, 'properties.snapshot')); await expect(properties).toMatchFileSnapshot(join(testDir, 'properties.snapshot'));
}); });
} }
} }

View File

@ -15,7 +15,7 @@ const compose = (entry) => {
return composeStories(entry); return composeStories(entry);
} catch (e) { } catch (e) {
throw new Error( throw new Error(
`There was an issue composing stories for the module: ${JSON.stringify(entry)}, ${e}`, `There was an issue composing stories for the module: ${JSON.stringify(entry)}, ${e}`
); );
} }
}; };
@ -23,7 +23,7 @@ const compose = (entry) => {
function getAllStoryFiles() { function getAllStoryFiles() {
// Place the glob you want to match your stories files // Place the glob you want to match your stories files
const storyFiles = glob.sync( const storyFiles = glob.sync(
path.join(__dirname, 'stories/**/*.{stories,story}.{js,jsx,mjs,ts,tsx}'), path.join(__dirname, 'stories/**/*.{stories,story}.{js,jsx,mjs,ts,tsx}')
); );
return storyFiles.map((filePath) => { return storyFiles.map((filePath) => {
@ -45,7 +45,7 @@ describe('Stories Snapshots', () => {
if (stories.length <= 0) { if (stories.length <= 0) {
throw new Error( throw new Error(
`No stories found for this module: ${title}. Make sure there is at least one valid story for this module.`, `No stories found for this module: ${title}. Make sure there is at least one valid story for this module.`
); );
} }
@ -157,7 +157,7 @@ const compose = (entry) => {
return composeStories(entry); return composeStories(entry);
} catch (error) { } catch (error) {
throw new Error( throw new Error(
`There was an issue composing stories for the module: ${JSON.stringify(entry)}, ${error}`, `There was an issue composing stories for the module: ${JSON.stringify(entry)}, ${error}`
); );
} }
}; };
@ -166,7 +166,7 @@ function getAllStoryFiles() {
const storyFiles = Object.entries( const storyFiles = Object.entries(
import.meta.glob('./stories/**/*.(stories|story).@(js|jsx|mjs|ts|tsx)', { import.meta.glob('./stories/**/*.(stories|story).@(js|jsx|mjs|ts|tsx)', {
eager: true, eager: true,
}), })
); );
return storyFiles.map(([filePath, storyFile]) => { return storyFiles.map(([filePath, storyFile]) => {
@ -185,7 +185,7 @@ describe('Stories Snapshots', () => {
if (stories.length <= 0) { if (stories.length <= 0) {
throw new Error( throw new Error(
`No stories found for this module: ${title}. Make sure there is at least one valid story for this module.`, `No stories found for this module: ${title}. Make sure there is at least one valid story for this module.`
); );
} }
@ -196,7 +196,7 @@ describe('Stories Snapshots', () => {
await new Promise((resolve) => setTimeout(resolve, 1)); await new Promise((resolve) => setTimeout(resolve, 1));
// Defines the custom snapshot path location and file name // Defines the custom snapshot path location and file name
const customSnapshotPath = `./__snapshots__/${componentName}.spec.js.snap`; const customSnapshotPath = `./__snapshots__/${componentName}.spec.js.snap`;
expect(document.body.firstChild).toMatchFileSnapshot(customSnapshotPath); await expect(document.body.firstChild).toMatchFileSnapshot(customSnapshotPath);
}); });
}); });
}); });
@ -226,7 +226,7 @@ const compose = (entry: StoryFile): ReturnType<typeof composeStories<StoryFile>>
return composeStories(entry); return composeStories(entry);
} catch (e) { } catch (e) {
throw new Error( throw new Error(
`There was an issue composing stories for the module: ${JSON.stringify(entry)}, ${e}`, `There was an issue composing stories for the module: ${JSON.stringify(entry)}, ${e}`
); );
} }
}; };
@ -236,7 +236,7 @@ function getAllStoryFiles() {
const storyFiles = Object.entries( const storyFiles = Object.entries(
import.meta.glob<StoryFile>('./stories/**/*.(stories|story).@(js|jsx|mjs|ts|tsx)', { import.meta.glob<StoryFile>('./stories/**/*.(stories|story).@(js|jsx|mjs|ts|tsx)', {
eager: true, eager: true,
}), })
); );
return storyFiles.map(([filePath, storyFile]) => { return storyFiles.map(([filePath, storyFile]) => {
@ -256,7 +256,7 @@ describe('Stories Snapshots', () => {
if (stories.length <= 0) { if (stories.length <= 0) {
throw new Error( throw new Error(
`No stories found for this module: ${title}. Make sure there is at least one valid story for this module.`, `No stories found for this module: ${title}. Make sure there is at least one valid story for this module.`
); );
} }
@ -267,7 +267,7 @@ describe('Stories Snapshots', () => {
await new Promise((resolve) => setTimeout(resolve, 1)); await new Promise((resolve) => setTimeout(resolve, 1));
// Defines the custom snapshot path location and file name // Defines the custom snapshot path location and file name
const customSnapshotPath = `./__snapshots__/${componentName}.spec.ts.snap`; const customSnapshotPath = `./__snapshots__/${componentName}.spec.ts.snap`;
expect(document.body.firstChild).toMatchFileSnapshot(customSnapshotPath); await expect(document.body.firstChild).toMatchFileSnapshot(customSnapshotPath);
}); });
}); });
}); });

View File

@ -18,9 +18,9 @@ describe(options.suite, () => {
const snapshotPath = path.join( const snapshotPath = path.join(
storyDir, storyDir,
options.snapshotsDirName, options.snapshotsDirName,
`${componentName}${options.snapshotExtension}`, `${componentName}${options.snapshotExtension}`
); );
expect(document.body.firstChild).toMatchFileSnapshot(snapshotPath); await expect(document.body.firstChild).toMatchFileSnapshot(snapshotPath);
}); });
}); });
}); });