Best JavaScript code snippet using storybook-test-runner
ProjectManager.ts
Source: ProjectManager.ts
1import _ from "lodash";2import vscode from "vscode";3import { Log } from "vscode-test-adapter-util";4import { createWorkspaceRootNode, WorkspaceRootNode } from "./helpers/tree";5import { JestTestAdapterOptions } from "./JestManager";6import { getSettings } from "./JestSettings";7import { getRepoParser, RepoParser } from "./repo";8import { ProjectChangeEvent, ProjectConfig } from "./repo/types";9import TestLoader from "./TestLoader";10import { EnvironmentChangedEvent, IDisposable, ProjectsChangedEvent, WorkspaceTestState } from "./types";11class ProjectManager {12 private repoParser: RepoParser | null = null;13 private testLoaders: TestLoader[] = [];14 private disposables: IDisposable[] = [];15 private projectsChangedEmitter: vscode.EventEmitter<ProjectsChangedEvent>;16 private workspaceTestState: WorkspaceRootNode = createWorkspaceRootNode();17 constructor(18 private readonly workspace: vscode.WorkspaceFolder,19 private readonly log: Log,20 private readonly options: JestTestAdapterOptions,21 ) {22 this.projectsChangedEmitter = new vscode.EventEmitter<ProjectsChangedEvent>();23 }24 public get projectsChanged() {25 return this.projectsChangedEmitter.event;26 }27 public async getTestState(): Promise<WorkspaceTestState> {28 await this.ensureInitialised();29 if (!this.repoParser) {30 // we return the default WorkspaceRootNode in the case we don't find a valid RepoParser.31 this.log.info(`No RepoParser available for project: ${this.workspace.uri.fsPath}`);32 return { suite: this.workspaceTestState };33 }34 const promises = this.testLoaders.map(t => t.getTestState(true));35 const testStates = await Promise.all(promises);36 this.workspaceTestState = {37 id: "root",38 label: `${this.workspace.name}`,39 projects: testStates.map(x => x.suite),40 type: "workspaceRootNode",41 };42 return { suite: this.workspaceTestState };43 }44 public dispose(): void {45 for (const disposable of this.testLoaders) {46 disposable.dispose();47 }48 this.testLoaders = [];49 for (const disposable of this.disposables) {50 disposable.dispose();51 }52 this.disposables = [];53 if (this.projectsChangedEmitter) {54 this.projectsChangedEmitter.dispose();55 }56 }57 private handleTestChange(event: EnvironmentChangedEvent) {58 switch (event.type) {59 case "App":60 // Assume that we don't need to update `this.workspaceTestState` because only App files have changed.61 this.projectsChangedEmitter.fire({62 invalidatedTestIds: event.invalidatedTestIds,63 suite: this.workspaceTestState,64 type: "projectAppUpdated",65 });66 this.log.info(`Application file changed: ${JSON.stringify(event)}`);67 break;68 case "Test":69 this.workspaceTestState = {70 ...this.workspaceTestState,71 projects: this.workspaceTestState.projects.map(p =>72 p.id !== event.updatedSuite.id ? p : event.updatedSuite,73 ),74 };75 this.projectsChangedEmitter.fire({76 suite: this.workspaceTestState,77 testEvent: event,78 type: "projectTestsUpdated",79 });80 this.log.info(`Test file changed: ${JSON.stringify(event)}`);81 break;82 }83 }84 private async ensureInitialised() {85 const jestPath = this.options.pathToJest(this.workspace);86 if (!this.repoParser) {87 this.repoParser = await getRepoParser(this.workspace.uri.fsPath, this.log, jestPath);88 89 if (this.repoParser) {90 this.disposables.push(this.repoParser.projectChange(e => this.handleProjectChange(e)));91 // register the test loaders for each project.92 const projects = await this.repoParser.getProjects();93 const createLoaderPromises = projects.map(async p => {94 await this.addNewTestLoader(p, jestPath);95 });96 await Promise.all(createLoaderPromises);97 }98 }99 }100 private async handleProjectChange(event: ProjectChangeEvent) {101 const jestPath = this.options.pathToJest(this.workspace);102 switch (event.type) {103 case "added":104 const loader = await this.addNewTestLoader(event.config, jestPath);105 const newProject = await loader.getTestState();106 this.workspaceTestState = {107 ...this.workspaceTestState,108 projects: this.workspaceTestState.projects109 .concat(newProject.suite)110 .sort((a, b) => a.id.localeCompare(b.id)),111 };112 this.projectsChangedEmitter.fire({113 addedProject: newProject.suite,114 suite: this.workspaceTestState,115 type: "projectAdded",116 });117 this.log.info(`New project added: ${event.config} ${newProject}`);118 break;119 case "removed":120 this.workspaceTestState = {121 ...this.workspaceTestState,122 projects: this.workspaceTestState.projects.filter(x => x.config.rootPath === event.rootPath),123 };124 this.projectsChangedEmitter.fire({125 suite: this.workspaceTestState,126 type: "projectRemoved",127 });128 this.log.info(`Project removed: ${event}`);129 break;130 }131 }132 private async addNewTestLoader(projectConfig: ProjectConfig, jestPath: string): Promise<TestLoader> {133 this.log.info(`Loading Jest settings from ${projectConfig.jestConfig}...`);134 const settings = await getSettings(projectConfig);135 if (settings.configs.length > 1) {136 this.log.info(`More than one Jest config found.`, settings);137 } else if (settings.configs[0]?.testRegex?.length > 1) {138 this.log.info(`More than one Jest test regex found.`, settings);139 }140 const testLoader = new TestLoader(settings, this.log, projectConfig);141 this.testLoaders.push(testLoader);142 this.disposables.push(testLoader.environmentChange(e => this.handleTestChange(e), this));143 return testLoader;144 }145}...
jest-exec.js
Source: jest-exec.js
1const {spawn} = require('child_process');2const {statSync} = require('fs');3const findUp = require('find-up');4const jestExec = (args = [], options = {}) => {5 const _jestPath = findUp.sync('node_modules/.bin/jest', {6 cwd: __dirname,7 });8 const _jestWindowsPath = _jestPath + '.cmd';9 let jestPath;10 try {11 statSync(_jestWindowsPath);12 jestPath = _jestWindowsPath;13 }14 catch (_) {15 jestPath = _jestPath;16 }17 const concat = stream => {18 return new Promise(resolve => {19 let value = '';20 stream.on('data', data => {value += data;});21 stream.on('end', () => {resolve(value);});22 });23 };24 return new Promise((resolve, reject) => {25 const child = spawn(26 jestPath,27 args,28 Object.assign({}, options, {29 env: Object.assign({}, process.env, {30 NODE_ENV: 'test',31 }, options.env),32 stdio: options.stdio || 'inherit',33 })34 );35 let stdout, stderr;36 if (options.stdio === 'pipe') {37 stdout = concat(child.stdout);38 stderr = concat(child.stderr);39 }40 child.on('exit', code => {41 Promise.all([stdout, stderr])42 .then(([stdout, stderr]) => {43 resolve({44 code,45 stdout,46 stderr,47 });48 });49 });50 });51};52const jestConfig = (args = [], options = {}) => {53 return jestExec(args.concat('--showConfig'), {stdio: 'pipe'})54 .then(({stdout}) => stdout)55 .then(JSON.parse);56};57jestExec.config = jestConfig;...
index.ts
Source: index.ts
1import { chain, Rule } from '@angular-devkit/schematics';2import { updateJsonInTree } from '@nrwl/workspace';3import { formatFiles } from '@nrwl/workspace';4import { get, set } from 'lodash';5import { join } from 'path';6function sortKeysAtJsonPath(path: string, jsonPath: string[]): Rule {7 return updateJsonInTree(path, (json) => {8 const unordered = get(json, jsonPath);9 const sorted = {};10 Object.keys(unordered).sort().forEach(key => {11 sorted[key] = unordered[key];12 });13 set(json, jsonPath, sorted);14 return json;15 });16}17function sortRootJest(): Rule {18 return (tree) => {19 const jestPath = 'jest.config.js';20 const contents = require(join(process.cwd(), jestPath));21 contents.projects.sort();22 tree.overwrite(jestPath, `23 module.exports = ${JSON.stringify(contents)};24 `);25 return tree;26 }27}28export default function (schema: any): Rule {29 return chain([30 sortKeysAtJsonPath('workspace.json', ['projects']),31 sortKeysAtJsonPath('nx.json', ['projects']),32 sortKeysAtJsonPath('tsconfig.base.json', ['compilerOptions', 'paths']),33 sortRootJest(),34 formatFiles()35 ]);...
Using AI Code Generation
1const storybookTestRunner = require('storybook-test-runner');2const jestPath = storybookTestRunner.jestPath;3const storybook = new storybookTestRunner.StorybookTestRunner({4 storybookPresetsOptions: {5 sassLoaderOptions: {6 },7 },8});
Using AI Code Generation
1import { jestPath } from 'storybook-test-runner';2describe('test', () => {3 it('test', () => {4 expect(true).toBe(true);5 });6});7export default jestPath;8import { configure } from '@storybook/react';9configure(require.context('../src', true, /\.stories\.js$/), module);10import { jestRunner } from 'storybook-test-runner';11jestRunner();12{13 "scripts": {14 }15}16const path = require('path');17const webpack = require('webpack');18const { jestPath } = require('storybook-test-runner');19module.exports = ({ config }) => {20 config.module.rules.push({21 test: /\.(ts|tsx)$/,22 {23 loader: require.resolve('awesome-typescript-loader'),24 options: {25 configFileName: path.resolve(__dirname, '../tsconfig.json'),26 },27 },28 {29 loader: require.resolve('react-docgen-typescript-loader'),30 },31 });32 config.resolve.extensions.push('.ts', '.tsx');33 config.plugins.push(34 new webpack.DefinePlugin({35 'process.env.jestPath': JSON.stringify(jestPath),36 }),37 );38 return config;
Using AI Code Generation
1const storybookTestRunner = require('storybook-test-runner').default;2const path = require('path');3const jestConfig = storybookTestRunner({4 storybookPath: path.resolve(__dirname, '../.storybook'),5 storybookStaticDir: path.resolve(__dirname, '../.out'),6 jestPath: path.resolve(__dirname, '../node_modules/.bin/jest'),7 storybookConfigDir: path.resolve(__dirname, '../.storybook'),8 storybookStaticDir: path.resolve(__dirname, '../.out'),9 storybookBuildDir: path.resolve(__dirname, '../.out'),10 storybookBuildStaticDir: path.resolve(__dirname, '../.out')11});12module.exports = jestConfig;13"scripts": {14 },15import { configure } from '@storybook/react';16import '../src/index.css';17const req = require.context('../src', true, /.stories.js$/);18function loadStories() {19 req.keys().forEach(filename => req(filename));20}21configure(loadStories, module);22const path = require('path');23module.exports = async ({ config, mode }) => {24 config.module.rules.push({25 test: /\.(ts|tsx)$/,26 loader: require.resolve('ts-loader')27 });28 config.resolve.extensions.push('.ts', '.tsx');29 return config;30};31{32}33{34 "compilerOptions": {
Using AI Code Generation
1import { jestPath } from 'storybook-test-runner'2const storybookPath = jestPath('src/**/*.stories.js')3module.exports = {4}5{6 "scripts": {7 }8}
Using AI Code Generation
1const { jestPath } = require('storybook-test-runner');2module.exports = jestPath('src');3"scripts": {4}5import { configure } from '@storybook/react';6import { setOptions } from '@storybook/addon-options';7import { setJestCucumberConfiguration } from 'storybook-addon-jest-cucumber';8import { configureJestStorybook } from 'storybook-test-runner';9configureJestStorybook();10setOptions({
Using AI Code Generation
1const { jestPath } = require('storybook-test-runner');2module.exports = {3 ...jestPath(),4};5const { jestPath } = require('storybook-test-runner');6module.exports = {7 ...jestPath({8 }),9};10import React from 'react';11import renderer from 'react-test-renderer';12import { Button } from 'components/Button/Button';13describe('Button', () => {14 it('renders correctly', () => {15 const tree = renderer.create(<Button>Click me</Button>).toJSON();16 expect(tree).toMatchSnapshot();17 });18});
Check out the latest blogs from LambdaTest on this topic:
I was once asked at a testing summit, “How do you manage a QA team using scrum?” After some consideration, I realized it would make a good article, so here I am. Understand that the idea behind developing software in a scrum environment is for development teams to self-organize.
With the rise of Agile, teams have been trying to minimize the gap between the stakeholders and the development team.
There is just one area where each member of the software testing community has a distinct point of view! Metrics! This contentious issue sparks intense disputes, and most conversations finish with no definitive conclusion. It covers a wide range of topics: How can testing efforts be measured? What is the most effective technique to assess effectiveness? Which of the many components should be quantified? How can we measure the quality of our testing performance, among other things?
Having a good web design can empower business and make your brand stand out. According to a survey by Top Design Firms, 50% of users believe that website design is crucial to an organization’s overall brand. Therefore, businesses should prioritize website design to meet customer expectations and build their brand identity. Your website is the face of your business, so it’s important that it’s updated regularly as per the current web design trends.
Hola Testers! Hope you all had a great Thanksgiving weekend! To make this time more memorable, we at LambdaTest have something to offer you as a token of appreciation.
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!