/*eslint-disable max-len, no-eval, prefer-arrow-callback, no-var*/ require('dotenv').config() const {resolve} = require('path') const {promises} = require('fs') // const jasmine2 = require('jest-jasmine2') const {remote} = require('webdriverio') const browserStackConfig = { user: process.env.BROWSERSTACK_USERNAME, key: process.env.BROWSERSTACK_ACCESS_KEY, services: ['browserstack'], // browserstackLocal: true, updateJob: true, strict: true, capabilities: { 'bstack:options': { // os: 'OS X', // osVersion: 'Mojave', // projectName: 'forest', // buildName: 'macos Safari', // seleniumVersion: '3.141.59', userName: process.env.BROWSERSTACK_USERNAME, accessKey: process.env.BROWSERSTACK_ACCESS_KEY, idleTimeout: 600, // local: 'true', // debug: 'true', // video: 'true', }, // browserName: 'Safari', // browserVersion: '12.1', // browserVersion: '79.0', // 'browserstack.localIdentifier': 'Test123', 'browserstack.use_w3c': true, // 'browserstack.local': true, 'browserstack.console': 'verbose', 'browserstack.idleTimeout': '600', acceptSslCert: true, // 'browserstack.networkLogs': true, }, logLevel: 'warn', coloredLogs: true, screenshotPath: './errorShots/', waitforTimeout: 20000, connectionRetryTimeout: 90000, connectionRetryCount: 3, host: 'hub.browserstack.com', } function createBrowserstackConfig(capabilities) { return { ...browserStackConfig, capabilities: { ...browserStackConfig.capabilities, ...capabilities, 'bstack:options': { ...browserStackConfig.capabilities['bstack:options'], ...capabilities['bstack:options'], }, }, } } if (!browserStackConfig.user || !browserStackConfig.key) { throw Error( `BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY env variables must be set`, ) } const effectorCjsPath = resolve( __dirname, '..', '..', 'npm', 'effector', 'effector.cjs.js', ) const effectorCompatPath = resolve( __dirname, '..', '..', 'npm', 'effector', 'compat.js', ) const forestPath = resolve( __dirname, '..', '..', 'npm', 'forest', 'forest.cjs.js', ) const polyfillPath = resolve( __dirname, '..', '..', 'node_modules', 'core-js-bundle', 'minified.js', ) const moduleRequests = { cjs: { path: effectorCjsPath, }, compat: { path: effectorCompatPath, }, forest: { path: forestPath, }, polyfill: { path: polyfillPath, }, } function moduleRequest(name, field, result) { if (!moduleRequests[name].req) { moduleRequests[name].req = promises.readFile( moduleRequests[name].path, 'utf8', ) } moduleRequests[name].req.then(code => { result[field] = code }) return moduleRequests[name].req } async function setSessionStatus(browser, status, reason) { const reasonString = JSON.stringify(reason) const script = `browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"${status}","reason": ${reasonString}}}` try { await browser.executeScript(script) } catch (error) {} } function noop() {} function projectName({displayName, id}) { if (typeof displayName === 'string') return displayName return (displayName && displayName.name) || id } module.exports = class BSTestRunner extends require('jest-runner').default { constructor(...args) { super(...args) this.isSerial = true } // jest drives this runner through the event emitter api, so the browser is // set up in a `test-file-start` listener: jest awaits those before running // the file, which is what makes the injected globals visible to it async runTests(tests, watcher, options) { const browserRequests = {} const testMap = {} function requestBrowser(tag, config) { if (!browserRequests[tag]) { testMap[tag] = {browser: null, fails: []} browserRequests[tag] = remote(createBrowserstackConfig(config)) // the rejection is reported by whoever awaits the request itself, // this branch only records the instance for the teardown browserRequests[tag].then(browser => { testMap[tag].browser = browser }, noop) } return browserRequests[tag] } const prepareTest = async test => { const { needForest, effectorBuild, needPolyfill, capabilitiesTag, capabilities, noAsyncAwait, } = test.context.config.globals let browser try { browser = await requestBrowser(capabilitiesTag, capabilities) } catch (error) { console.error('remote() call error', error) if (error && error.message) throw Error(`remote error: ${error.message}`) throw error } const initBrowser = async () => { try { await browser.url('about:blank') await browser.execute(initPageRuntime, modulesList) } catch (error) { console.error('initBrowser error', error) throw error } } const libs = {} const moduleRequests = [] if (needPolyfill) { moduleRequests.push(moduleRequest('polyfill', 'polyfill', libs)) } moduleRequests.push(moduleRequest(effectorBuild, 'effector', libs)) if (needForest) { moduleRequests.push(moduleRequest('forest', 'forest', libs)) } await Promise.all(moduleRequests) const modulesList = [] if (needPolyfill) { modulesList.push({ name: 'polyfill', src: libs.polyfill, }) } modulesList.push({ name: 'effector', src: libs.effector, }) if (needForest) { modulesList.push({ name: 'forest', src: libs.forest, }) } // if (browser.isChrome) browser.takeHeapSnapshot const execFunc = async cb => { let cbText = typeof cb === 'function' ? cb.toString() : cb if (noAsyncAwait) { const {transformSync} = require('@babel/core') cbText = transformSync(cbText, { babelrc: false, filename: 'execFunc.js', sourceType: 'script', sourceMaps: false, presets: [ [ '@babel/preset-env', { loose: true, useBuiltIns: 'entry', corejs: 3, modules: false, shippedProposals: true, targets: ['Chrome 47', 'IE 11'], }, ], ], plugins: [ [ 'babel-plugin-transform-async-to-promises', { inlineHelpers: true, }, ], ], }).code.slice(1, -2) } const result = await browser.executeAsync(execAsyncCode, cbText) if (Object(result).error) { throw result.error } return result } const exec = cb => execFunc(`async () => { await (${typeof cb === 'function' ? cb.toString() : cb})() return domSnapshots }`).then(result => { if (Array.isArray(result)) { const prettyHtml = require('../../src/fixtures/prettyHtml') return result.map(prettyHtml) } return result }) test.context.config = { ...test.context.config, globals: { ...test.context.config.globals, browser, execFunc, exec, initBrowser, }, } } const trackFailure = (test, error) => { const tag = test.context.config.globals.capabilitiesTag if (testMap[tag]) { testMap[tag].fails.push(`[${tag}] ${projectName(test.context.config)}`) } console.error('test file failure:', error) } const listeners = [ this.on('test-file-start', ([test]) => prepareTest(test)), this.on('test-file-failure', ([test, error]) => trackFailure(test, error)), ] try { return await super.runTests(tests, watcher, options) } finally { for (const removeListener of listeners) removeListener() const instances = Object.values(testMap).filter(e => !!e.browser) if (instances.length > 0) { await Promise.all( instances.map(async ({browser, fails}) => { if (fails.length > 0) { await setSessionStatus( browser, 'failed', `Failed tests (${fails.length}): ${fails.join('|')}`, ) } else { await setSessionStatus(browser, 'passed', '') } try { await browser.deleteSession() } catch (err) {} }), ) } } } } function execAsyncCode(cb, done) { console.log('cb', cb) try { var evaluated = eval('(' + cb + ')()') return Promise.resolve(evaluated) .then(function (result) { done(result) }) .catch(function (error) { document.body.innerHTML = '