Best JavaScript code snippet using jest
index.js
Source:index.js  
...121    assert(rest.length === 0);122    if (content === null) {123      assert(expectedStderr === null);124      assert(125        cleanStderr(stderrLogs).length === 0,126        util.inspect({ stderrLogs })127      );128      return;129    }130    assert(content.constructor === String);131    expectedStderr = expectedStderr || [];132    expectedStderr.push(content);133  };134  if (debugMode) {135    console.log(chalk.bold.blue("[DEBUG-MODE] Enabled."));136  }137  const log_collector = new LogCollector({ debugMode });138  log_collector.enable();139  const { stdoutLogs, stderrLogs } = log_collector;140  let testFailure;141  try {142    await testFn({ ...testArgs, assertStderr });143  } catch (err) {144    testFailure = err;145  } finally {146    log_collector.disable();147  }148  try {149    if (testFailure) throw testFailure;150    await checkStderr({ expectedStderr, stderrLogs });151    if (!debugMode) {152      await checkStdout(stdoutLogs);153    }154  } catch (err) {155    log_collector.flush();156    console.error(err);157    console.log(colorError(symbolError + "Failed test: " + testName));158    throw new Error("Tests failed.");159  }160  // Delete all cookies161  await testArgs.browserEval(() => {162    window.deleteAllCookies();163    assert(document.cookie === "");164  });165  console.log(symbolSuccess + testName);166  return;167}168async function checkStderr({ expectedStderr, stderrLogs }) {169  // Express seems to rethrow errors asyncronously; we need to wait for express to rethrow errors.170  await new Promise((r) => setTimeout(r, 0));171  stderrLogs = cleanStderr(stderrLogs);172  const stderrLogsLength = stderrLogs.length;173  checkIfErrorIsExpected(stderrLogs);174  stderrLogs.forEach(checkErrorFormat);175  assert(expectedStderr === null || expectedStderr.length >= 1);176  if (expectedStderr === null) {177    assert(178      stderrLogsLength === 0,179      util.inspect({180        expectedLength: 0,181        stderrLogsLength,182        stderrLogs,183      })184    );185    return;186  }187  assert(stderrLogs.length === stderrLogsLength);188  assert(189    stderrLogs.length === expectedStderr.length,190    util.inspect({ stderrLogs, expectedStderr })191  );192  stderrLogs.forEach((stderrLog, i) => {193    const stderrContent = expectedStderr[i];194    assert(195      stderrLog.includes(stderrContent),196      util.inspect({197        expectedStderr: stderrContent,198        actualStderr: stderrLog,199      })200    );201  });202  return;203  function checkErrorFormat(stderrLog) {204    assert(stderrLog.constructor === String);205    const [firstLine, ...errorStackLines] = stderrLog.split("\n");206    // Always start with a single-line error message207    if (208      !firstLine.includes("[Telefunc][Wrong Usage] ") &&209      !firstLine.includes("[EXPECTED_ERROR]")210    ) {211      console.log(stderrLog);212      assert(false);213    }214    // Always show a stack trace215    if (errorStackLines.length <= 5) {216      console.log(stderrLog);217      assert(false);218    }219    // Rest is stack trace220    errorStackLines.forEach((errStackLine) => {221      if (errStackLine === "") {222        return;223      }224      if (stripAnsi(errStackLine).startsWith("    at")) {225        return;226      }227      console.log("==Error:");228      console.log(stderrLog);229      console.log("==Line:");230      console.log(errStackLine);231      assert(false);232    });233    // Stack trace should never show @brillout/assert trace234    assert(!stripAnsi(stderrLog).includes("@brillout/assert"));235    assert(!stripAnsi(stderrLog).includes("@brillout/libassert"));236  }237  function checkIfErrorIsExpected(stderrLogs) {238    stderrLogs.forEach((stderrLog) => {239      // No test should throw an internal errors240      // => re-throw, interupt the test run, and show the error241      if (stderrLog.includes("[Internal Error]")) {242        throw stderrLog;243      }244      // It is expected that test can throw a [Wrong Usage] or245      // an error constructed by the test itself ([EXPECTED_ERROR])246      if (247        stderrLog.includes("[Telefunc][Wrong Usage]") ||248        stderrLog.includes("[EXPECTED_ERROR]")249      ) {250        return;251      }252      // It seems like these pesting `JSHandle@error` can be circumvented253      // by logging `err.stack` instead of `err`.254      if (stderrLog.includes("JSHandle@error")) {255        console.log(stderrLog);256        assert(257          false,258          "Make sure to `console.error(err.stack)` instead of `console.error(err)` in `browserEval`"259        );260      }261      // Any other error are unexpected262      console.log("Unexpected error type:");263      console.log(stderrLog);264      assert(false, "Unexpected kind of error.");265    });266  }267}268async function checkStdout(stdoutLogs) {269  stdoutLogs = cleanStdout(stdoutLogs);270  assert(stdoutLogs.length === 0);271}272function cleanStdout(stdoutLogs) {273  return removeHiddenLog(stdoutLogs);274}275function cleanStderr(stderrLogs) {276  return removeHiddenLog(removeNetworkErrorLogs(stderrLogs));277}278function removeHiddenLog(stdLogs) {279  return stdLogs.filter(280    (log) =>281      !log ||282      !log.includes(283        // Puppeteer "hidden" log (never saw such hidden log before; I don't know how and why this exists)284        "This conditional evaluates to true if and only if there was an error"285      )286  );287}288function removeNetworkErrorLogs(stdLogs) {289  return stdLogs.filter(...test.js
Source:test.js  
1'use strict'2/* globals describe beforeEach it afterEach */3const chai = require('chai')4chai.use(require('chai-as-promised'))5const expect = chai.expect6const nock = require('nock')7nock.disableNetConnect()8const mock = require('mock-fs')9const rewire = require('rewire')10const fs = require('fs')11const path = require('path')12const co = require('co')13const stdin = require('mock-stdin').stdin()14// heroku stuff15const cli = require('heroku-cli-util')16const commands = require('./index').commands17// things I'm testing18const merge = require('./util/merge')19const file = rewire('./util/file')20const header = file.__get__('header')21// HELPERS22const fetchCMD = name => {23  return commands.find(c => c.command === name)24}25// heroku-cli err output depends on terminal width, so we have to standardize26const cleanStdErr = s => {27  return s.replace(/\n|â¸| {2,}/g, '').trim()28}29const setup = () => {30  cli.raiseErrors = true31  cli.exit.mock()32}33const defaultFS = () => {34  // this is so I can setup without affecting other tests35  return {36    '.env': fixtures.local_file,37    windows: fixtures.windows_file,38    'other.txt': fixtures.local_file,39    dnt: mock.file({ mode: '000' }),40    multiline: fixtures.multiline_file,41    tricky_multiline: fixtures.tricky_multiline_file,42    expanded: fixtures.expanded_file43  }44}45// https://glebbahmutov.com/blog/unit-testing-cli-programs/46const mockInput = i => {47  process.nextTick(() => {48    stdin.send(i)49  })50}51// val must be true or false52const mockSettingsFile = val => {53  const location = path.join(process.env.HOME, '.heroku_config_settings.json')54  fs.writeFileSync(location, fixtures[`settings_obj_${val}`])55}56const nockFetchConfig = appName => {57  appName = appName || 'test'58  nock('https://api.heroku.com:443')59    .get(`/apps/${appName}/config-vars`)60    .reply(200, fixtures.remote_obj)61}62// FIXTURES63const fixtures = {64  remote_obj: {65    NODE_ENV: 'pRoDuction',66    NAME: 'david',67    SOURCE: 'remote'68  },69  local_obj: {70    NODE_ENV: 'test',71    SOURCE: 'local',72    DB_STRING: 'mongo://blah@thing.mongo.thing.com:4567'73  },74  remote_win_obj: {75    NODE_ENV: 'pRoDuction',76    SOURCE: 'remote',77    DB_STRING: 'mongo://blah@thing.mongo.thing.com:4567',78    NAME: 'david'79  },80  local_win_obj: {81    NODE_ENV: 'test',82    SOURCE: 'local',83    DB_STRING: 'mongo://blah@thing.mongo.thing.com:4567',84    NAME: 'david'85  },86  remote_cleaned_obj: {87    NODE_ENV: 'pRoDuction',88    SOURCE: 'remote',89    DB_STRING: 'mongo://blah@thing.mongo.thing.com:4567'90  },91  multiline_obj: {92    SECRET_KEY:93      '-----BEGIN RSA PRIVATE KEY-----\nMIIrandomtext\nmorerandomtext\n-----END RSA PRIVATE KEY-----',94    OTHER_KEY: 'blahblah',95    ITS_GONNA_BE: 'legend wait for it...\ndary'96  },97  tricky_multiline_obj: {98    SECRET_KEY:99      '-----BEGIN RSA PRIVATE KEY-----\nMIIrandomtext\nmorerandomtext==\n-----END RSA PRIVATE KEY-----',100    OTHER_KEY: 'blahblah',101    ITS_GONNA_BE: 'legend wait for it...\ndary'102  },103  expanded_obj: {104    'na-me': 'david',105    'integration.url': 'https://google.com'106  },107  local_file:108    '#comment\nNODE_ENV= test\nSOURCE =local\nSOURCE = local\nDB_STRING="mongo://blah@thing.mongo.thing.com:4567"\n',109  windows_file:110    '#comment\r\nNODE_ENV= test\r\nSOURCE =local\r\nSOURCE = local\r\nDB_STRING=mongo://blah@thing.mongo.thing.com:4567\r\n',111  merged_local_file:112    header +113    'DB_STRING="mongo://blah@thing.mongo.thing.com:4567"\nNAME="david"\nNODE_ENV="test"\nSOURCE="local"\n',114  multiline_file:115    'SECRET_KEY="-----BEGIN RSA PRIVATE KEY-----\nMIIrandomtext\n\nmorerandomtext\n-----END RSA PRIVATE KEY-----"\nOTHER_KEY=blahblah\nITS_GONNA_BE="legend wait for it...\n# you better not be lactose intolerant cause it\'s\ndary"',116  tricky_multiline_file:117    'SECRET_KEY="-----BEGIN RSA PRIVATE KEY-----\nMIIrandomtext\n\nmorerandomtext==\n-----END RSA PRIVATE KEY-----"\nOTHER_KEY=blahblah\nITS_GONNA_BE="legend wait for it...\n# you better not be lactose intolerant cause it\'s\ndary"',118  expanded_file: 'na-me=david\nintegration.url=https://google.com\n',119  // test both quote styles120  sample_file:121    header +122    'export PIZZA="Abo\'s"\nNAME="david"\n\n#this is a comment!\nCITY=boulder\n\n\n',123  clean_sample_file: header + 'CITY="boulder"\nNAME="david"\nPIZZA="Abo\'s"\n',124  naked_clean_sample_file: header + "CITY=boulder\nNAME=david\nPIZZA=Abo's\n",125  sample_obj: { NAME: 'david', CITY: 'boulder', PIZZA: "Abo's" },126  settings_obj_true: JSON.stringify({ blah: true }),127  settings_obj_false: JSON.stringify({ blah: false })128}129// TESTS130setup()131describe('Merging', () => {132  it('should overwrite local with remote', () => {133    expect(merge(fixtures.local_obj, fixtures.remote_obj, {})).to.deep.equal(134      fixtures.remote_win_obj135    )136  })137  it('should overwrite remote with local', () => {138    expect(merge(fixtures.remote_obj, fixtures.local_obj, {})).to.deep.equal(139      fixtures.local_win_obj140    )141  })142  it('should overwrite local with remote w/override', () => {143    expect(144      merge(fixtures.remote_obj, fixtures.local_obj, { overwrite: true })145    ).to.deep.equal(fixtures.remote_win_obj)146  })147  it('should overwrite remote with local w/override', () => {148    expect(149      merge(fixtures.local_obj, fixtures.remote_obj, { overwrite: true })150    ).to.deep.equal(fixtures.local_win_obj)151  })152})153describe('Reading', () => {154  beforeEach(() => {155    mock(defaultFS())156    cli.mockConsole()157  })158  it('should return empty object from non-existant file', () => {159    return expect(file.read('asdf')).to.eventually.deep.equal({})160  })161  it('should read a local file', () => {162    return expect(file.read('.env')).to.eventually.deep.equal(163      fixtures.local_obj164    )165  })166  it('should read a local windows file', () => {167    return expect(file.read('windows')).to.eventually.deep.equal(168      fixtures.local_obj169    )170  })171  it('should read multiline values (and multi-multiline values)', () => {172    return expect(file.read('multiline')).to.eventually.deep.equal(173      fixtures.multiline_obj174    )175  })176  it('should read multiline values (and multi-multiline values)', () => {177    return expect(file.read('tricky_multiline')).to.eventually.deep.equal(178      fixtures.tricky_multiline_obj179    )180  })181  it('should warn about duplicate keys', () => {182    return file.read('.env').then(() => {183      expect(cleanStdErr(cli.stderr)).to.include(184        '"SOURCE" is in env file twice'185      )186    })187  })188  it('should skip warnings in quiet mode', () => {189    return file.read('.env', { quiet: true }).then(() => {190      expect(cli.stderr).to.equal('')191    })192  })193  it('should warn when it hits a malformed line', () => {194    return file.read('expanded').then(() => {195      expect(cleanStdErr(cli.stderr)).to.include('unable to parse line')196    })197  })198  it('should read expanded files', () => {199    return expect(200      file.read('expanded', { expanded: true })201    ).to.eventually.deep.equal(fixtures.expanded_obj)202  })203  afterEach(() => {204    mock.restore()205    cli.mockConsole(false)206  })207})208describe('Writing', () => {209  beforeEach(() => {210    cli.mockConsole()211    mock(defaultFS())212  })213  it('should fail to write to a file it lacks permissions for', () => {214    return expect(file.write({}, 'dnt')).to.be.rejectedWith(Error)215  })216  const fname = '.env'217  it('should successfully write a file, louldly', () => {218    return file.write(fixtures.sample_obj).then(() => {219      const res = fs.readFileSync(fname, 'utf-8')220      expect(res).to.equal(fixtures.clean_sample_file)221      expect(cli.stdout).to.not.equal('')222    })223  })224  it('should successfully write a file, quietly', () => {225    // need to pass all params if i'm passing quiet mode226    return file.write(fixtures.sample_obj, fname, { quiet: true }).then(() => {227      const res = fs.readFileSync(fname, 'utf-8')228      expect(res).to.equal(fixtures.clean_sample_file)229      expect(cli.stdout).to.equal('')230    })231  })232  afterEach(() => {233    mock.restore()234    cli.mockConsole(false)235  })236})237describe('Transforming', () => {238  it('should decode files correctly', () => {239    expect(240      file.__get__('objFromFileFormat')(fixtures.sample_file)241    ).to.deep.equal(fixtures.sample_obj)242  })243  it('should encode file correctly', () => {244    expect(file.__get__('objToFileFormat')(fixtures.sample_obj)).to.equal(245      fixtures.clean_sample_file246    )247  })248  it('should read unquoted files', () => {249    expect(250      file.__get__('objFromFileFormat')(fixtures.naked_clean_sample_file)251    ).to.deep.equal(fixtures.sample_obj)252  })253  it('should write unquoted files', () => {254    expect(255      file.__get__('objToFileFormat')(fixtures.sample_obj, { unquoted: true })256    ).to.equal(fixtures.naked_clean_sample_file)257  })258})259describe('Checking for Prod', () => {260  beforeEach(() => {261    cli.mockConsole()262  })263  it('should delete prod when prompted', () => {264    mockInput('d')265    return co(file.shouldDeleteProd({ app: 'test' })).then(shouldDelete => {266      expect(shouldDelete).to.equal(true)267    })268  })269  it('should ignore prod when prompted', () => {270    mockInput('i')271    return co(file.shouldDeleteProd({ app: 'test' })).then(shouldDelete => {272      expect(shouldDelete).to.equal(false)273    })274  })275  it('should read a true settings file if able', () => {276    const testMode = true277    mock()278    mockSettingsFile(testMode)279    return co(file.shouldDeleteProd({ app: 'blah' })).then(shouldDelete => {280      expect(shouldDelete).to.equal(testMode)281    })282  })283  it('should read a false settings file if able', () => {284    const testMode = false285    mock()286    mockSettingsFile(testMode)287    return co(file.shouldDeleteProd({ app: 'blah' })).then(shouldDelete => {288      expect(shouldDelete).to.equal(testMode)289    })290  })291  afterEach(() => {292    cli.mockConsole(false)293    mock.restore()294  })295})296describe.skip('Pushing', () => {297  beforeEach(() => {298    cli.mockConsole()299    mock(defaultFS())300  })301  const cmd = fetchCMD('push')302  const fname = 'other.txt'303  it('should correctly push configs w/ flags', () => {304    nockFetchConfig()305    // this will fail if we don't pass the correct body, as intended306    nock('https://api.heroku.com:443')307      .patch('/apps/test/config-vars', fixtures.remote_win_obj)308      .reply(200, fixtures.remote_win_obj)309    return cmd310      .run({ flags: { file: fname, quiet: true }, app: 'test' })311      .then(() => {312        expect(nock.isDone()).to.equal(true)313        expect(cli.stdout).to.equal('')314      })315  })316  it('should correctly push null values for unused configs', () => {317    nockFetchConfig()318    // this will fail if we don't pass the correct body, as intended319    nock('https://api.heroku.com:443')320      .patch('/apps/test/config-vars', fixtures.remote_win_obj)321      .reply(200, fixtures.remote_win_obj)322    // delete call323    nock('https://api.heroku.com:443')324      .patch('/apps/test/config-vars', { NAME: null })325      .reply(200, fixtures.remote_cleaned_obj)326    return cmd.run({ flags: { clean: true }, app: 'test' }).then(() => {327      expect(nock.isDone()).to.equal(true)328    })329  })330  afterEach(() => {331    mock.restore()332    cli.mockConsole(false)333  })334})335// the following tests are broken because mock-fs v4 doesn't support lazy336//   requires and mock-fs v3 only supports up to node 7. What I need is a mocked337//   filesystem that uses the real fs for requires, even when mocked338describe.skip('Pulling', () => {339  beforeEach(() => {340    cli.mockConsole()341    mock(defaultFS())342  })343  const cmd = fetchCMD('pull')344  it('should correctly pull configs', () => {345    const fname = 'other.txt'346    nockFetchConfig()347    return cmd.run({ flags: { file: fname }, app: 'test' }).then(() => {348      const res = fs.readFileSync(fname, 'utf-8')349      expect(res).to.include(fixtures.merged_local_file)350    })351  })352  describe('skipping production value', () => {353    const fname = '.env'354    const appName = 'blah'355    it('should delete value', () => {356      mockSettingsFile(true)357      nockFetchConfig(appName)358      return cmd.run({ flags: { overwrite: true }, app: appName }).then(() => {359        const res = fs.readFileSync(fname, 'utf-8')360        expect(res).not.to.include('pRoDuction')361      })362    })363    it('should not delete value', () => {364      mockSettingsFile(false)365      nockFetchConfig(appName)366      return cmd.run({ flags: { overwrite: true }, app: appName }).then(() => {367        const res = fs.readFileSync(fname, 'utf-8')368        expect(res).to.include('pRoDuction')369      })370    })371  })372  afterEach(() => {373    mock.restore()374    cli.mockConsole(false)375  })...database.js
Source:database.js  
1import mysql from 'promise-mysql'2import { version } from 'react'3import { cmdPromise } from './utils'4import { isEmpty } from './utils'5// CLI Resources:6// https://dev.mysql.com/doc/refman/8.0/en/mysql-command-options.html7// https://mariadb.com/kb/en/library/mysqldump/8// A better solution than dropping and recreating the db.9// It also avoids errors when run on an empty database.10// https://stackoverflow.com/a/1862554511const dropDbQuery = `SET FOREIGN_KEY_CHECKS = 0;SET GROUP_CONCAT_MAX_LEN=32768;SET @tables = NULL;SELECT GROUP_CONCAT('\`', table_name, '\`') INTO @tables FROM information_schema.tables WHERE table_schema = (SELECT DATABASE()); SELECT IFNULL(@tables,'dummy') INTO @tables; SET @tables = CONCAT('DROP TABLE IF EXISTS ', @tables); PREPARE stmt FROM @tables; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET FOREIGN_KEY_CHECKS = 1;`12const importDbQuery = ({13    host = 'localhost',14    port = 3306,15    user,16    password,17    database,18    importFile,19}) =>20    `mysql --host='${host}' --port='${21        !isEmpty(port) ? port : 330622    }' --user='${user}' --password='${password}' ${database} < ${importFile};`23// Clear out the tables in a database24const doDropAllDbTables = async config => {25    let errorMessage26    const defaultConfig = {27        multipleStatements: true,28        host: null,29        user: null,30        password: null,31        database: null,32    }33    // Create the connection to the local database34    const conn = await mysql35        .createConnection({ ...defaultConfig, ...config })36        .catch(error => (errorMessage = error))37    if (errorMessage) return new Error(errorMessage)38    conn.query(dropDbQuery)39    conn.end()40}41const doImportDb = async config => {42    let errorMessage43    await cmdPromise(importDbQuery(config)).catch(e => (errorMessage = e))44    if (errorMessage) return new Error(errorMessage)45}46const doLocalDbDump = async config => {47    let errorMessage48    config = Object.assign(config, {49        isMysql8: await isMysql8({50            localCmd:cmdPromise51        })52    })53    await cmdPromise(getDbDumpZipCommands(config)).catch(54        e => (errorMessage = e)55    )56    if (errorMessage) return new Error(errorMessage)57}58const getDbDumpZipCommands = ({59    host = 'localhost',60    port = 3306,61    user,62    password,63    database,64    gzipFilePath,65    isMysql8 = false66}) =>67    // Dump and zip the db - this can make it around 9 times smaller68    `mysqldump --host='${host}' --port='${port}' --user='${user}' --password='${password}' --single-transaction --lock-tables=false --no-tablespaces ${isMysql8?'--column-statistics=0':''} ${database} | gzip > '${gzipFilePath}'`69const checkForDb = async ({ dbFilePath, sshConn }) => {70    let errorMessage71    // Check the local database file has been uploaded72    await sshConn73        .execCommand(`test -f ${dbFilePath} && echo "true" || echo "false"`)74        .then(({ stdout, stderr }) => {75            // If error running command76            if (stderr)77                return (errorMessage = `There was an issue checking the presence of the remote db dump\n\n${stderr}`)78            // If db dump doesn't exist79            if (stdout && String(stdout).includes('false'))80                return (errorMessage = `The remote db dump wasn't found`)81        })82    if (errorMessage) return new Error(errorMessage)83    return84}85const unzipDb = async ({ dbFilePath, sshConn }) => {86    let errorMessage87    // -d : decompress / -f : force overwrite any existing file88    await sshConn89        .execCommand(`gzip -df '${dbFilePath}'`)90        .then(({ stdout, stderr }) => {91            // If error running command92            if (stderr)93                return (errorMessage = `There was an issue checking the presence of the remote db dump\n\n${stderr}`)94            // If db dump doesn't exist95            if (stdout && String(stdout).includes('false'))96                return (errorMessage = `The remote db dump wasn't found`)97        })98    if (errorMessage) return new Error(errorMessage)99    return100}101// Drop the tables in the remote database to prepare for import102const clearDb = async ({ remoteEnv, sshConn }) => {103    let errorMessage104    const connectSql = `mysql --host="${remoteEnv.DB_SERVER}" --user="${105        remoteEnv.DB_USER106    }" --port="${remoteEnv.DB_PORT}" --database="${107        remoteEnv.DB_DATABASE108    }" --password="${remoteEnv.DB_PASSWORD}"`109    await sshConn110        .execCommand(111            `${connectSql} -Nse 'show tables' ${112                remoteEnv.DB_DATABASE113            } | while read table; do ${connectSql} -e "SET FOREIGN_KEY_CHECKS = 0; truncate table $table; SET FOREIGN_KEY_CHECKS = 1;" ${114                remoteEnv.DB_DATABASE115            }; done`116        )117        .then(({ stdout, stderr }) => {118            const cleanMessage = message =>119                String(message)120                    .replace(121                        // Suppress this warning - it's not as bad as it sounds122                        /mysql: \[Warning] Using a password on the command line interface can be insecure./g,123                        ''124                    )125                    .trim()126            const cleanStderr = stderr ? cleanMessage(stderr) : false127            if (cleanStderr)128                errorMessage = `There was an issue attempting to clear the remote database\n\n${cleanStderr}`129        })130    if (errorMessage) return new Error(errorMessage)131    return132}133const importDb = async ({ remoteEnv, dbFilePath, sshConn }) => {134    let errorMessage135    // Import the local database into the remote with mysql136    await sshConn137        .execCommand(138            importDbQuery({139                host: remoteEnv.DB_SERVER,140                port: remoteEnv.DB_PORT,141                user: remoteEnv.DB_USER,142                password: remoteEnv.DB_PASSWORD,143                database: remoteEnv.DB_DATABASE,144                importFile: dbFilePath,145            })146        )147        .then(({ stdout, stderr }) => {148            const cleanMessage = message =>149                String(message)150                    .replace(151                        // Suppress this warning - it's not as bad as it sounds152                        /mysql: \[Warning] Using a password on the command line interface can be insecure./g,153                        ''154                    )155                    .trim()156            const cleanStderr = stderr ? cleanMessage(stderr) : false157            if (cleanStderr)158                errorMessage = `There was an issue importing the local db dump on the remote server\n\n${cleanStderr}`159        })160    if (errorMessage) return new Error(errorMessage)161    return162}163// Cleanup the database dump file on the remote164const removeDb = async ({ dbFilePath, sshConn }) => {165    let errorMessage166    // Import the local database into the remote with mysql167    await sshConn.execCommand(`rm ${dbFilePath}`).then(({ stdout, stderr }) => {168        // If error running command169        if (stderr)170            errorMessage = `There was an issue importing the local db dump on the remote server\n\n${stderr}`171    })172    if (errorMessage) return new Error(errorMessage)173    return174}175// Check the version of mysqldump (mysql)176// cmd can be either177// - sshConn(remote)178// or179// - localCmd(local)180const isMysql8 = async ({sshConn, localCmd}) => {181    if (sshConn) {182        let output = "", errorMessage = "";183        await sshConn.execCommand(`mysqldump --version`).then(({ stdout, stderr }) => {184            output = stdout;185            // If error running command186            if (stderr)187                errorMessage = `There was an issue checking mysql version\n\n${stderr}`188        })189        if (output.indexOf("Ver 8") !== -1) {190            return true;191        }192        return false;193    } else if (localCmd) {194        let output = "", errorMessage = "";195        await localCmd(`mysqldump --version`).then(stdout => {196            output = stdout;197        }).catch(stderr => {198            // If error running command199            if (stderr)200                errorMessage = `There was an issue checking mysql version\n\n${stderr}`201        }) 202        if (output.indexOf("Ver 8") !== -1) {203            return true;204        }205        return false;206    }207    return false;208}209export {210    getDbDumpZipCommands,211    doDropAllDbTables,212    dropDbQuery,213    doImportDb,214    doLocalDbDump,215    importDbQuery,216    checkForDb,217    unzipDb,218    clearDb,219    importDb,220    removeDb,221    isMysql8,...globals.test.js
Source:globals.test.js  
...17  writeFiles,18} from '../Utils';19const DIR = path.resolve(os.tmpdir(), 'global-variables.test');20const TEST_DIR = path.resolve(DIR, '__tests__');21function cleanStderr(stderr) {22  const {rest} = extractSummary(stderr);23  return rest.replace(/.*(jest-jasmine2).*\n/g, '');24}25beforeEach(() => {26  cleanup(DIR);27  createEmptyPackage(DIR);28});29afterAll(() => cleanup(DIR));30test('basic test constructs', () => {31  const filename = 'basic.test-constructs.test.js';32  const content = `33    it('it', () => {});34    test('test', () => {});35    describe('describe', () => {36      it('it', () => {});37      test('test', () => {});38    });39  `;40  writeFiles(TEST_DIR, {[filename]: content});41  const {stderr, status} = runJest(DIR);42  expect(status).toBe(0);43  const {summary, rest} = extractSummary(stderr);44  expect(rest).toMatchSnapshot();45  expect(summary).toMatchSnapshot();46});47test('skips', () => {48  const filename = 'skips-constructs.test.js';49  const content = `50    it('it', () => {});51    xtest('xtest', () => {});52    xit('xit', () => {});53    it.skip('it.skip', () => {});54    test.skip('test.skip', () => {});55    xdescribe('xdescribe', () => {56      it('it', () => {});57      test('test', () => {});58    });59    describe.skip('describe.skip', () => {60      test('test', () => {});61      describe('describe', () => {62        test('test', () => {});63      });64    });65  `;66  writeFiles(TEST_DIR, {[filename]: content});67  const {stderr, status} = runJest(DIR);68  const {summary, rest} = extractSummary(stderr);69  expect(rest).toMatchSnapshot();70  expect(summary).toMatchSnapshot();71  expect(status).toBe(0);72});73test('only', () => {74  const filename = 'only-constructs.test.js';75  const content = `76    it('it', () => {});77    test.only('test.only', () => {});78    it.only('it.only', () => {});79    fit('fit', () => {});80    fdescribe('fdescribe', () => {81      it('it', () => {});82      test('test', () => {});83    });84    describe.only('describe.only', () => {85      test('test', () => {});86      describe('describe', () => {87        test('test', () => {});88      });89    });90  `;91  writeFiles(TEST_DIR, {[filename]: content});92  const {stderr, status} = runJest(DIR);93  expect(status).toBe(0);94  const {summary, rest} = extractSummary(stderr);95  expect(rest).toMatchSnapshot();96  expect(summary).toMatchSnapshot();97});98test('cannot have describe with no implementation', () => {99  const filename = 'only-constructs.test.js';100  const content = `101    describe('describe, no implementation');102  `;103  writeFiles(TEST_DIR, {[filename]: content});104  const {stderr, status} = runJest(DIR);105  expect(status).toBe(1);106  const rest = cleanStderr(stderr);107  const {summary} = extractSummary(stderr);108  expect(rest).toMatchSnapshot();109  expect(summary).toMatchSnapshot();110});111test('cannot test with no implementation', () => {112  const filename = 'only-constructs.test.js';113  const content = `114    it('it', () => {});115    it('it, no implementation');116    test('test, no implementation');117  `;118  writeFiles(TEST_DIR, {[filename]: content});119  const {stderr, status} = runJest(DIR);120  expect(status).toBe(1);121  const {summary} = extractSummary(stderr);122  expect(cleanStderr(stderr)).toMatchSnapshot();123  expect(summary).toMatchSnapshot();124});125test('skips with expand arg', () => {126  const filename = 'skips-constructs.test.js';127  const content = `128    it('it', () => {});129    xtest('xtest', () => {});130    xit('xit', () => {});131    it.skip('it.skip', () => {});132    test.skip('test.skip', () => {});133    xdescribe('xdescribe', () => {134      it('it', () => {});135      test('test', () => {});136    });137    describe.skip('describe.skip', () => {138      test('test', () => {});139      describe('describe', () => {140        test('test', () => {});141      });142    });143  `;144  writeFiles(TEST_DIR, {[filename]: content});145  const {stderr, status} = runJest(DIR, ['--expand']);146  expect(status).toBe(0);147  const {summary, rest} = extractSummary(stderr);148  expect(rest).toMatchSnapshot();149  expect(summary).toMatchSnapshot();150});151test('only with expand arg', () => {152  const filename = 'only-constructs.test.js';153  const content = `154    it('it', () => {});155    test.only('test.only', () => {});156    it.only('it.only', () => {});157    fit('fit', () => {});158    fdescribe('fdescribe', () => {159      it('it', () => {});160      test('test', () => {});161    });162    describe.only('describe.only', () => {163      test('test', () => {});164      describe('describe', () => {165        test('test', () => {});166      });167    });168  `;169  writeFiles(TEST_DIR, {[filename]: content});170  const {stderr, status} = runJest(DIR, ['--expand']);171  expect(status).toBe(0);172  const {summary, rest} = extractSummary(stderr);173  expect(rest).toMatchSnapshot();174  expect(summary).toMatchSnapshot();175});176test('cannot test with no implementation with expand arg', () => {177  const filename = 'only-constructs.test.js';178  const content = `179    it('it', () => {});180    it('it, no implementation');181    test('test, no implementation');182  `;183  writeFiles(TEST_DIR, {[filename]: content});184  const {stderr, status} = runJest(DIR, ['--expand']);185  expect(status).toBe(1);186  const {summary} = extractSummary(stderr);187  expect(cleanStderr(stderr)).toMatchSnapshot();188  expect(summary).toMatchSnapshot();189});190test('function as descriptor', () => {191  const filename = 'function-as-descriptor.test.js';192  const content = `193    function Foo() {}194    describe(Foo, () => {195      it('it', () => {});196    });197  `;198  writeFiles(TEST_DIR, {[filename]: content});199  const {stderr, status} = runJest(DIR);200  expect(status).toBe(0);201  const {summary, rest} = extractSummary(stderr);...failures.test.js
Source:failures.test.js  
...11import runJest from '../runJest';12import {wrap} from 'jest-snapshot-serializer-raw';13const dir = path.resolve(__dirname, '../failures');14const normalizeDots = text => text.replace(/\.{1,}$/gm, '.');15function cleanStderr(stderr) {16  const {rest} = extractSummary(stderr);17  return rest18    .replace(/.*(jest-jasmine2|jest-circus).*\n/g, '')19    .replace(new RegExp('Failed: Object {', 'g'), 'thrown: Object {');20}21test('not throwing Error objects', () => {22  let stderr;23  stderr = runJest(dir, ['throwNumber.test.js']).stderr;24  expect(wrap(cleanStderr(stderr))).toMatchSnapshot();25  stderr = runJest(dir, ['throwString.test.js']).stderr;26  expect(wrap(cleanStderr(stderr))).toMatchSnapshot();27  stderr = runJest(dir, ['throwObject.test.js']).stderr;28  expect(wrap(cleanStderr(stderr))).toMatchSnapshot();29  stderr = runJest(dir, ['assertionCount.test.js']).stderr;30  expect(wrap(cleanStderr(stderr))).toMatchSnapshot();31  stderr = runJest(dir, ['duringTests.test.js']).stderr;32  expect(wrap(cleanStderr(stderr))).toMatchSnapshot();33});34test('works with node assert', () => {35  const nodeMajorVersion = Number(process.versions.node.split('.')[0]);36  const {stderr} = runJest(dir, ['assertionError.test.js']);37  let summary = normalizeDots(cleanStderr(stderr));38  // Node 9 started to include the error for `doesNotThrow`39  // https://github.com/nodejs/node/pull/1216740  if (nodeMajorVersion >= 9) {41    expect(summary).toContain(`42    assert.doesNotThrow(function)43    Expected the function not to throw an error.44    Instead, it threw:45      [Error: err!]46    Message:47      Got unwanted exception.48`);49    expect(summary).toContain(`50      69 | 51      70 | test('assert.doesNotThrow', () => {52    > 71 |   assert.doesNotThrow(() => {53         |          ^54      72 |     throw Error('err!');55      73 |   });56      74 | });57      at Object.doesNotThrow (__tests__/assertionError.test.js:71:10)58`);59    const commonErrorMessage = `Message:60      Got unwanted exception.61`;62    if (nodeMajorVersion === 9) {63      const specificErrorMessage = `Message:64      Got unwanted exception.65    err!66`;67      expect(summary).toContain(specificErrorMessage);68      summary = summary.replace(specificErrorMessage, commonErrorMessage);69    } else {70      const specificErrorMessage = `Message:71      Got unwanted exception.72    Actual message: "err!"73`;74      expect(summary).toContain(specificErrorMessage);75      summary = summary.replace(specificErrorMessage, commonErrorMessage);76    }77  }78  if (nodeMajorVersion >= 10) {79    const ifErrorMessage = `80    assert.ifError(received, expected)81    Expected value ifError to:82      null83    Received:84      185    Message:86      ifError got unwanted exception: 187    Difference:88      Comparing two different types of values. Expected null but received number.89      65 | 90      66 | test('assert.ifError', () => {91    > 67 |   assert.ifError(1);92         |          ^93      68 | });94      69 | 95      70 | test('assert.doesNotThrow', () => {96      at Object.ifError (__tests__/assertionError.test.js:67:10)97`;98    expect(summary).toContain(ifErrorMessage);99    summary = summary.replace(ifErrorMessage, '');100  } else {101    const ifErrorMessage = `102    thrown: 1103      64 | });104      65 | 105    > 66 | test('assert.ifError', () => {106         | ^107      67 |   assert.ifError(1);108      68 | });109      69 | 110      at Object.test (__tests__/assertionError.test.js:66:1)111`;112    expect(summary).toContain(ifErrorMessage);113    summary = summary.replace(ifErrorMessage, '');114  }115  expect(wrap(summary)).toMatchSnapshot();116});117test('works with assertions in separate files', () => {118  const {stderr} = runJest(dir, ['testMacro.test.js']);119  expect(wrap(normalizeDots(cleanStderr(stderr)))).toMatchSnapshot();120});121test('works with async failures', () => {122  const {stderr} = runJest(dir, ['asyncFailures.test.js']);123  const rest = cleanStderr(stderr)124    .split('\n')125    .filter(line => line.indexOf('packages/expect/build/index.js') === -1)126    .join('\n');127  // Remove replacements when jasmine is gone128  const result = normalizeDots(rest)129    .replace(/.*thrown:.*\n/, '')130    .replace(/.*Use jest\.setTimeout\(newTimeout\).*/, '<REPLACED>')131    .replace(/.*Timeout - Async callback was not.*/, '<REPLACED>');132  expect(wrap(result)).toMatchSnapshot();133});134test('works with snapshot failures', () => {135  const {stderr} = runJest(dir, ['snapshot.test.js']);136  const result = normalizeDots(cleanStderr(stderr));137  expect(138    wrap(result.substring(0, result.indexOf('Snapshot Summary'))),139  ).toMatchSnapshot();140});141test('works with named snapshot failures', () => {142  const {stderr} = runJest(dir, ['snapshotNamed.test.js']);143  const result = normalizeDots(cleanStderr(stderr));144  expect(145    wrap(result.substring(0, result.indexOf('Snapshot Summary'))),146  ).toMatchSnapshot();...build.js
Source:build.js  
1const exec = require('child_process').exec;2async function runNpmCommand(command) {3    //const { stdout, stderr } = await exec(`npm run ${command}`);4    return new Promise((resolve, reject) => {5        const start = process.hrtime();6        exec(`yarn run ${command}`, (error, stdout, stderr) => {7            if (error) {8                reject({ error: stderr, out: stdout });9                return;10            }11            let cleanStdErr = cleanErr(stderr);12            if (cleanStdErr) {13                reject({ error: cleanStdErr, out: stdout });14                return;15            }16            const elapsed = process.hrtime(start);17            resolve({ out: stdout, time: elapsed });18        });19    });20}21async function runBuildStep(comment, command) {22    process.stdout.write(comment);23    const result = await runNpmCommand(command);24    process.stdout.write(`done (${formatTime(result.time)})\n`);25    return result;26}27function formatTime(time) {28    const seconds = time[0];29    const min = Math.trunc(seconds / 60);30    const secondsLeft = seconds - min * 60;31    return `${min}m ${secondsLeft}s`;32}33function cleanErr(stderr) {34    return (stderr || '').split('\n')35        .filter(x => x.replace(' ', '').replace('\r', '').length > 0) //clean empty strings36        .filter(x => !x.startsWith('npm WARN')) //clean npm warnings;37        .join('\n');38}39async function build() {40    try {41        await runBuildStep('Fixing style...', 'lint_fix');42        await runBuildStep('Linting...', 'lint');43        await runBuildStep('Building server...', 'build_server');44        await runBuildStep('Building client...', 'build_client');45    } catch (err) {46        process.stdout.write("error\n");47        if (err.out) {48            console.error('STDOUT:');49            console.error(err.out.toString());50        }51        console.error('STDERR:');52        console.error(err.error.toString());53        process.exit(1);54    }55}...release.js
Source:release.js  
1// Create a tag using the current server package version and push the tag to origin2const { version } = require("../../packages/server/package.json");3const { exec } = require("child_process");4const { exit } = require("process");5release();6async function release() {7  console.log(`[tag] clean up v${version}`);8  const { error: cleanError, stderr: cleanStderr } = await runShell(`git tag -d v${version}`, { dir: __dirname });9  if (cleanError || cleanStderr) {10    console.log(`[tag] nothing to clean up, continue`);11  }12  console.log(`[tag] add v${version}`);13  const { error: addError, stderr: addStderr } = await runShell(`git tag v${version}`, { dir: __dirname });14  if (addError || addStderr) {15    console.error("[tag] add failed");16    console.error("[tag] error code", addError?.code);17    console.error("[tag] error msg", addStderr);18    exit(1);19  }20  console.log(`[tag] push v${version}`);21  const { stdout: pushStdout, error: pushError, stderr: pushStderr } = await runShell(`git push origin v${version}`, { dir: __dirname });22  if (pushError) { // Git writes to stderr even when successful23    console.error("[tag] push failed");24    console.error("[tag] error code", pushError?.code);25    console.error("[tag] error msg", pushStderr);26    exit(1);27  }28  console.log(pushStderr ?? pushStdout ?? "No output. Something might be wrong.");29}30async function runShell(command, options) {31  return new Promise((resolve) => {32    exec(command, options, (error, stdout, stderr) =>33      resolve({34        error,35        stdout,36        stderr,37      })38    );39  });...LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.
|<p>it('check_object_of_Car', () => {</p><p>    expect(newCar()).toBeInstanceOf(Car);</p><p> });</p>|
| :- |
Get 100 minutes of automation test minutes FREE!!
