Best JavaScript code snippet using storybook-test-runner
index.js
Source:index.js
1"use strict"2// builtin tooling3const path = require("path")4// internal tooling5const joinMedia = require("./lib/join-media")6const resolveId = require("./lib/resolve-id")7const loadContent = require("./lib/load-content")8const processContent = require("./lib/process-content")9const parseStatements = require("./lib/parse-statements")10function AtImport(options) {11 options = {12 root: process.cwd(),13 path: [],14 skipDuplicates: true,15 resolve: resolveId,16 load: loadContent,17 plugins: [],18 addModulesDirectories: [],19 ...options,20 }21 options.root = path.resolve(options.root)22 // convert string to an array of a single element23 if (typeof options.path === "string") options.path = [options.path]24 if (!Array.isArray(options.path)) options.path = []25 options.path = options.path.map(p => path.resolve(options.root, p))26 return {27 postcssPlugin: "postcss-import",28 Once(styles, { result, atRule, postcss }) {29 const state = {30 importedFiles: {},31 hashFiles: {},32 }33 if (styles.source && styles.source.input && styles.source.input.file) {34 state.importedFiles[styles.source.input.file] = {}35 }36 if (options.plugins && !Array.isArray(options.plugins)) {37 throw new Error("plugins option must be an array")38 }39 return parseStyles(result, styles, options, state, []).then(bundle => {40 applyRaws(bundle)41 applyMedia(bundle)42 applyStyles(bundle, styles)43 })44 function applyRaws(bundle) {45 bundle.forEach((stmt, index) => {46 if (index === 0) return47 if (stmt.parent) {48 const { before } = stmt.parent.node.raws49 if (stmt.type === "nodes") stmt.nodes[0].raws.before = before50 else stmt.node.raws.before = before51 } else if (stmt.type === "nodes") {52 stmt.nodes[0].raws.before = stmt.nodes[0].raws.before || "\n"53 }54 })55 }56 function applyMedia(bundle) {57 bundle.forEach(stmt => {58 if (!stmt.media.length || stmt.type === "charset") return59 if (stmt.type === "import") {60 stmt.node.params = `${stmt.fullUri} ${stmt.media.join(", ")}`61 } else if (stmt.type === "media")62 stmt.node.params = stmt.media.join(", ")63 else {64 const { nodes } = stmt65 const { parent } = nodes[0]66 const mediaNode = atRule({67 name: "media",68 params: stmt.media.join(", "),69 source: parent.source,70 })71 parent.insertBefore(nodes[0], mediaNode)72 // remove nodes73 nodes.forEach(node => {74 node.parent = undefined75 })76 // better output77 nodes[0].raws.before = nodes[0].raws.before || "\n"78 // wrap new rules with media query79 mediaNode.append(nodes)80 stmt.type = "media"81 stmt.node = mediaNode82 delete stmt.nodes83 }84 })85 }86 function applyStyles(bundle, styles) {87 styles.nodes = []88 // Strip additional statements.89 bundle.forEach(stmt => {90 if (["charset", "import", "media"].includes(stmt.type)) {91 stmt.node.parent = undefined92 styles.append(stmt.node)93 } else if (stmt.type === "nodes") {94 stmt.nodes.forEach(node => {95 node.parent = undefined96 styles.append(node)97 })98 }99 })100 }101 function parseStyles(result, styles, options, state, media) {102 const statements = parseStatements(result, styles)103 return Promise.resolve(statements)104 .then(stmts => {105 // process each statement in series106 return stmts.reduce((promise, stmt) => {107 return promise.then(() => {108 stmt.media = joinMedia(media, stmt.media || [])109 // skip protocol base uri (protocol://url) or protocol-relative110 if (111 stmt.type !== "import" ||112 /^(?:[a-z]+:)?\/\//i.test(stmt.uri)113 ) {114 return115 }116 if (options.filter && !options.filter(stmt.uri)) {117 // rejected by filter118 return119 }120 return resolveImportId(result, stmt, options, state)121 })122 }, Promise.resolve())123 })124 .then(() => {125 let charset126 const imports = []127 const bundle = []128 function handleCharset(stmt) {129 if (!charset) charset = stmt130 // charsets aren't case-sensitive, so convert to lower case to compare131 else if (132 stmt.node.params.toLowerCase() !==133 charset.node.params.toLowerCase()134 ) {135 throw new Error(136 `Incompatable @charset statements:137 ${stmt.node.params} specified in ${stmt.node.source.input.file}138 ${charset.node.params} specified in ${charset.node.source.input.file}`139 )140 }141 }142 // squash statements and their children143 statements.forEach(stmt => {144 if (stmt.type === "charset") handleCharset(stmt)145 else if (stmt.type === "import") {146 if (stmt.children) {147 stmt.children.forEach((child, index) => {148 if (child.type === "import") imports.push(child)149 else if (child.type === "charset") handleCharset(child)150 else bundle.push(child)151 // For better output152 if (index === 0) child.parent = stmt153 })154 } else imports.push(stmt)155 } else if (stmt.type === "media" || stmt.type === "nodes") {156 bundle.push(stmt)157 }158 })159 return charset160 ? [charset, ...imports.concat(bundle)]161 : imports.concat(bundle)162 })163 }164 function resolveImportId(result, stmt, options, state) {165 const atRule = stmt.node166 let sourceFile167 if (atRule.source && atRule.source.input && atRule.source.input.file) {168 sourceFile = atRule.source.input.file169 }170 const base = sourceFile171 ? path.dirname(atRule.source.input.file)172 : options.root173 return Promise.resolve(options.resolve(stmt.uri, base, options))174 .then(paths => {175 if (!Array.isArray(paths)) paths = [paths]176 // Ensure that each path is absolute:177 return Promise.all(178 paths.map(file => {179 return !path.isAbsolute(file)180 ? resolveId(file, base, options)181 : file182 })183 )184 })185 .then(resolved => {186 // Add dependency messages:187 resolved.forEach(file => {188 result.messages.push({189 type: "dependency",190 plugin: "postcss-import",191 file,192 parent: sourceFile,193 })194 })195 return Promise.all(196 resolved.map(file => {197 return loadImportContent(result, stmt, file, options, state)198 })199 )200 })201 .then(result => {202 // Merge loaded statements203 stmt.children = result.reduce((result, statements) => {204 return statements ? result.concat(statements) : result205 }, [])206 })207 }208 function loadImportContent(result, stmt, filename, options, state) {209 const atRule = stmt.node210 const { media } = stmt211 if (options.skipDuplicates) {212 // skip files already imported at the same scope213 if (214 state.importedFiles[filename] &&215 state.importedFiles[filename][media]216 ) {217 return218 }219 // save imported files to skip them next time220 if (!state.importedFiles[filename]) state.importedFiles[filename] = {}221 state.importedFiles[filename][media] = true222 }223 return Promise.resolve(options.load(filename, options)).then(224 content => {225 if (content.trim() === "") {226 result.warn(`${filename} is empty`, { node: atRule })227 return228 }229 // skip previous imported files not containing @import rules230 if (state.hashFiles[content] && state.hashFiles[content][media])231 return232 return processContent(233 result,234 content,235 filename,236 options,237 postcss238 ).then(importedResult => {239 const styles = importedResult.root240 result.messages = result.messages.concat(importedResult.messages)241 if (options.skipDuplicates) {242 const hasImport = styles.some(child => {243 return child.type === "atrule" && child.name === "import"244 })245 if (!hasImport) {246 // save hash files to skip them next time247 if (!state.hashFiles[content]) state.hashFiles[content] = {}248 state.hashFiles[content][media] = true249 }250 }251 // recursion: import @import from imported file252 return parseStyles(result, styles, options, state, media)253 })254 }255 )256 }257 },258 }259}260AtImport.postcss = true...
widget.js
Source:widget.js
1(function($) {2 var csscls = PhpDebugBar.utils.makecsscls('phpdebugbar-widgets-');3 /**4 * Widget for the displaying sql queries5 *6 * Options:7 * - data8 */9 var SQLQueriesWidget = PhpDebugBar.Widgets.SQLQueriesWidget = PhpDebugBar.Widget.extend({10 className: csscls('sqlqueries'),11 onFilterClick: function(el) {12 $(el).toggleClass(csscls('excluded'));13 var excludedLabels = [];14 this.$toolbar.find(csscls('.filter') + csscls('.excluded')).each(function() {15 excludedLabels.push(this.rel);16 });17 this.$list.$el.find("li[connection=" + $(el).attr("rel") + "]").toggle();18 this.set('exclude', excludedLabels);19 },20 render: function() {21 this.$status = $('<div />').addClass(csscls('status')).appendTo(this.$el);22 this.$toolbar = $('<div></div>').addClass(csscls('toolbar')).appendTo(this.$el);23 var filters = [], self = this;24 this.$list = new PhpDebugBar.Widgets.ListWidget({ itemRenderer: function(li, stmt) {25 $('<code />').addClass(csscls('sql')).html(PhpDebugBar.Widgets.highlight(stmt.sql, 'sql')).appendTo(li);26 if (stmt.duration_str) {27 $('<span title="Duration" />').addClass(csscls('duration')).text(stmt.duration_str).appendTo(li);28 }29 if (stmt.memory_str) {30 $('<span title="Memory usage" />').addClass(csscls('memory')).text(stmt.memory_str).appendTo(li);31 }32 if (typeof(stmt.row_count) != 'undefined') {33 $('<span title="Row count" />').addClass(csscls('row-count')).text(stmt.row_count).appendTo(li);34 }35 if (typeof(stmt.stmt_id) != 'undefined' && stmt.stmt_id) {36 $('<span title="Prepared statement ID" />').addClass(csscls('stmt-id')).text(stmt.stmt_id).appendTo(li);37 }38 if (stmt.connection) {39 $('<span title="Connection" />').addClass(csscls('database')).text(stmt.connection).appendTo(li);40 li.attr("connection",stmt.connection);41 if ( $.inArray(stmt.connection, filters) == -1 ) {42 filters.push(stmt.connection);43 $('<a />')44 .addClass(csscls('filter'))45 .text(stmt.connection)46 .attr('rel', stmt.connection)47 .on('click', function() { self.onFilterClick(this); })48 .appendTo(self.$toolbar);49 if (filters.length>1) {50 self.$toolbar.show();51 self.$list.$el.css("margin-bottom","20px");52 }53 }54 }55 if (typeof(stmt.is_success) != 'undefined' && !stmt.is_success) {56 li.addClass(csscls('error'));57 li.append($('<span />').addClass(csscls('error')).text("[" + stmt.error_code + "] " + stmt.error_message));58 }59 if (stmt.params && !$.isEmptyObject(stmt.params)) {60 var table = $('<table><tr><th colspan="2">Params</th></tr></table>').addClass(csscls('params')).appendTo(li);61 for (var key in stmt.params) {62 if (typeof stmt.params[key] !== 'function') {63 table.append('<tr><td class="' + csscls('name') + '">' + key + '</td><td class="' + csscls('value') +64 '">' + stmt.params[key] + '</td></tr>');65 }66 }67 li.css('cursor', 'pointer').click(function() {68 if (table.is(':visible')) {69 table.hide();70 } else {71 table.show();72 }73 });74 }75 }});76 this.$list.$el.appendTo(this.$el);77 this.bindAttr('data', function(data) {78 this.$list.set('data', data.statements);79 this.$status.empty();80 // Search for duplicate statements.81 for (var sql = {}, unique = 0, i = 0; i < data.statements.length; i++) {82 var stmt = data.statements[i].sql;83 if (data.statements[i].params && !$.isEmptyObject(data.statements[i].params)) {84 stmt += ' {' + $.param(data.statements[i].params, false) + '}';85 }86 sql[stmt] = sql[stmt] || { keys: [] };87 sql[stmt].keys.push(i);88 }89 // Add classes to all duplicate SQL statements.90 for (var stmt in sql) {91 if (sql[stmt].keys.length > 1) {92 unique++;93 for (var i = 0; i < sql[stmt].keys.length; i++) {94 this.$list.$el.find('.' + csscls('list-item')).eq(sql[stmt].keys[i])95 .addClass(csscls('sql-duplicate')).addClass(csscls('sql-duplicate-'+unique));96 }97 }98 }99 var t = $('<span />').text(data.nb_statements + " statements were executed").appendTo(this.$status);100 if (data.nb_failed_statements) {101 t.append(", " + data.nb_failed_statements + " of which failed");102 }103 if (unique) {104 t.append(", " + (data.nb_statements - unique) + " of which were duplicated");105 t.append(", " + unique + " unique");106 }107 if (data.accumulated_duration_str) {108 this.$status.append($('<span title="Accumulated duration" />').addClass(csscls('duration')).text(data.accumulated_duration_str));109 }110 if (data.memory_usage_str) {111 this.$status.append($('<span title="Memory usage" />').addClass(csscls('memory')).text(data.memory_usage_str));112 }113 });114 }115 });...
ext-air-db.js
Source:ext-air-db.js
1/*!2 * Ext JS Library 3.0.03 * Copyright(c) 2006-2009 Ext JS, LLC4 * licensing@extjs.com5 * http://www.extjs.com/license6 */7 Ext.data.AirDB = Ext.extend(Ext.data.SqlDB, {8 open : function(db, cb, scope){9 this.conn = new air.SQLConnection();10 var file = air.File.applicationResourceDirectory.resolve(db);11 this.conn.addEventListener(air.SQLEvent.OPEN, this.onOpen.createDelegate(this, [cb, scope]));12 this.conn.addEventListener(air.SQLEvent.CLOSE, this.onClose.createDelegate(this));13 this.conn.open(file, true);14 },15 close : function(){16 this.conn.close();17 },18 onOpen : function(cb, scope){19 this.openState = true;20 Ext.callback(cb, scope, [this]);21 this.fireEvent('open', this);22 },23 onClose : function(){24 this.fireEvent('close', this);25 },26 onError : function(e, stmt, type, cb, scope){27 Ext.callback(cb, scope, [false, e, stmt]);28 },29 onResult : function(e, stmt, type, cb, scope){30 if(type == 'exec'){31 Ext.callback(cb, scope, [true, e, stmt]);32 }else{33 var r = [];34 var result = stmt.getResult();35 if(result && result.data){36 var len = result.data.length;37 for(var i = 0; i < len; i++) {38 r[r.length] = result.data[i];39 }40 }41 Ext.callback(cb, scope, [r, e, stmt]);42 }43 },44 createStatement : function(type, cb, scope){45 var stmt = new air.SQLStatement();46 stmt.addEventListener(air.SQLErrorEvent.ERROR, this.onError.createDelegate(this, [stmt, type, cb, scope], true));47 stmt.addEventListener(air.SQLEvent.RESULT, this.onResult.createDelegate(this, [stmt, type, cb, scope], true));48 stmt.sqlConnection = this.conn;49 return stmt;50 },51 exec : function(sql, cb, scope){52 var stmt = this.createStatement('exec', cb, scope);53 stmt.text = sql;54 stmt.execute();55 },56 execBy : function(sql, args, cb, scope){57 var stmt = this.createStatement('exec', cb, scope);58 stmt.text = sql;59 this.addParams(stmt, args);60 stmt.execute();61 },62 query : function(sql, cb, scope){63 var stmt = this.createStatement('query', cb, scope);64 stmt.text = sql;65 stmt.execute(this.maxResults);66 },67 queryBy : function(sql, args, cb, scope){68 var stmt = this.createStatement('query', cb, scope);69 stmt.text = sql;70 this.addParams(stmt, args);71 stmt.execute(this.maxResults);72 },73 addParams : function(stmt, args){74 if(!args){ return; }75 for(var key in args){76 if(args.hasOwnProperty(key)){77 if(!isNaN(key)){78 stmt.parameters[parseInt(key)+1] = args[key];79 }else{80 stmt.parameters[':' + key] = args[key];81 }82 }83 }84 return stmt;85 }...
Using AI Code Generation
1import { stmt } from 'storybook-test-runner';2stmt('test', () => {3});4import { storiesOf } from '@storybook/react';5import { withTests } from '@storybook/addon-jest';6import results from './test-results.json';7storiesOf('test', module)8 .addDecorator(9 withTests({10 filesExt: '((\\.specs?)|(\\.tests?))?(\\.ts|\\.tsx)?$'11 })12 .add('test', () => <div></div>);13{14 "summary": {15 "snapshot": {16 },17 {18 {19 }20 }21 }22}
Using AI Code Generation
1import { stmt } from 'storybook-test-runner';2import MyComponent from './MyComponent';3describe('MyComponent', () => {4 it('should render', () => {5 stmt(<MyComponent />)6 })7});8import React from 'react';9function MyComponent() {10 return (11}12export default MyComponent;13import React from 'react';14import MyComponent from './MyComponent';15export default {16};17export const myComponent = () => <MyComponent />18import { configure } from '@storybook/react';19import 'storybook-test-runner/register'20function loadStories() {21 require('../stories');22}23configure(loadStories, module);24module.exports = ({ config }) => {25 config.module.rules.push({26 loaders: [require.resolve('@storybook/source-loader')],27 });28 return config;29};30import 'storybook-test-runner/register';31{32 "scripts": {33 },34 "devDependencies": {
Using AI Code Generation
1import { stmt } from 'storybook-test-runner'2describe('Test suite', () => {3 it('Test case', () => {4 stmt('Hello World')5 })6})7import { storybookTestRunner } from 'storybook-test-runner'8storybookTestRunner({9 {10 },11})12import { storybookTestRunner } from 'storybook-test-runner'13storybookTestRunner({14 {15 {16 {17 },18 },19 {20 {21 },22 },23 },24})25import { storybookTestRunner } from 'storybook-test-runner'26storybookTestRunner({27 {28 {29 {30 {31 },32 },33 },34 },35})36import { storybookTestRunner } from 'storybook-test-runner'37storybookTestRunner({38 {39 {40 {41 {
Using AI Code Generation
1import { stmt } from 'storybook-test-runner'2stmt('test that fails', () => {3 expect(1).toBe(2)4})5stmt('test that passes', () => {6 expect(1).toBe(1)7})8import React from 'react'9import { storiesOf } from '@storybook/react'10import { withTests } from 'storybook-addon-jest'11import results from './test-results.json'12import './test.stories.css'13storiesOf('test', module)14 .addDecorator(withTests({ results }))15 .add('test that fails', () => <div>test that fails</div>)16 .add('test that passes', () => <div>test that passes</div>)17 {18 },19 {20 }21.test {22 margin: 10px;23}24.test .test__passed {25 color: green;26}27.test .test__failed {28 color: red;29}30 "devDependencies": {31 },32 "jest": {33 },34 "sonar": {
Using AI Code Generation
1stmt('console.log("Hello World")');2stmt('console.log("Hello World")');3stmt('console.log("Hello World")');4stmt('console.log("Hello World")');5stmt('console.log("Hello World")');6stmt('console.log("Hello World")');7stmt('console.log("Hello World")');8stmt('console.log("Hello World")');9stmt('console.log("Hello World")');10stmt('console.log("Hello World")');11stmt('console.log("Hello World")');
Using AI Code Generation
1const { stmt } = require('storybook-test-runner');2stmt('My Storybook Test', ({ story, storybook }) => {3 story('My Story', () => {4 storybook('My Story', () => {5 });6 });7});8const { test } = require('storybook-test-runner');9test('My Storybook Test', ({ story, storybook }) => {10 story('My Story', () => {11 storybook('My Story', () => {12 });13 });14});15const { testStory } = require('storybook-test-runner');16testStory('My Storybook Test', ({ story, storybook }) => {17 story('My Story', () => {18 storybook('My Story', () => {19 });20 });21});22const { testStories } = require('storybook-test-runner');23testStories('My Storybook Test', ({ story, storybook }) => {24 story('My Story', () => {25 storybook('My Story', () => {26 });27 });28});29const { testStorybook } = require('storybook-test-runner');30testStorybook('My Storybook Test', ({ story, storybook }) => {31 story('My Story', () => {32 storybook('My Story', () => {33 });34 });35});36const { testStorybooks } = require('storybook-test-runner');37testStorybooks('My Storybook Test', ({ story, storybook }) => {38 story('My Story', () => {39 storybook('My Story', () => {40 });41 });42});43const { testStorybookTest } = require('storybook-test-runner');44testStorybookTest('My Storybook Test', ({ story, storybook }) => {45 story('My Story', () =>
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!!