How to use pathToPackage method in Cypress

Best JavaScript code snippet using cypress

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

index.js

Source: index.js Github

copy
1#!/usr/bin/env node
2const shell = require('shelljs');
3let pathToPackage = require('global-modules-path').getPath('git-safe');
4switch (process.argv[2]) {
5  case 'encrypt':
6    {
7      shell.exec(`bash ${pathToPackage}/git-safe.sh encrypt ${pathToPackage}`);
8    }
9    break;
10  case 'decrypt':
11    {
12      shell.exec(`bash ${pathToPackage}/git-safe.sh decrypt ${pathToPackage}`);
13    }
14    break;
15  case 'commit':
16    {
17      shell.exec(`bash ${pathToPackage}/git-safe.sh commit ${pathToPackage}`);
18    }
19    break;
20  default: {
21    console.log(
22      '[git-safe]: Only `git-safe encrypt | git-safe decrypt | git-safe commit` are supported !'
23    );
24  }
25}
26
Full Screen

mock-backend.js

Source: mock-backend.js Github

copy
1#! /usr/bin/env node
2/**
3 *  Script to run wiremock based on specific stub jar downloaded from local machine or if not found from nexus.
4 *
5 *  Download sources:
6 *    1) local machine .m2 repository
7 *    2) nexus artifactory
8 *
9 *  Required params:
10 *    stubs - path to direct stubs jar link
11 *      uk/co/hl/bf/working-day-calendar/0.2.9-SNAPSHOT/working-day-calendar-0.2.9-20180112.122824-2-stubs.jar
12 *    port - port of wiremock to serve mocks
13 *      9000
14 *
15 *  Example of use in project package.json:
16 *    node ./mock/mock-backend.js stubs=uk/co/hl/bf/working-day-calendar/0.2.9-SNAPSHOT/working-day-calendar-0.2.9-20180112.122824-2-stubs.jar port=9000"
17 */
18
19const NPMRC_CA_PARAM_NAME = "ca";
20const MAVEN_REPO = "https://nexus.hltech.dev/repository/maven-public/";
21
22const fs = require('fs');
23const request = require('request');
24const unzip = require('unzip');
25const execSync = require('child_process').execSync;
26
27const dir = './stubs';
28const jarDir = dir + '/stubs.jar';
29const mappingsDir = dir + '/mappings';
30
31cleanStubs(dir);
32createBaseStubFolder();
33downloadStubsJarAndRunWireMock(getParam('stubs'));
34
35function downloadStubsJarAndRunWireMock(stubsPath) {
36  createJarFromLocalM2Source(
37    stubsPath,
38    createJarFromNexusSource
39  )
40}
41
42function createJarFromLocalM2Source(stubsPath, alternative) {
43  const pathToPackage = getUserHome() + '/.m2/repository/' + stubsPath;
44  console.log("Looking for jar in local", pathToPackage);
45  fs.readFile(pathToPackage, (err, data) => {
46    if (err) {
47      alternative(stubsPath);
48      return
49    }
50    fs.writeFile(jarDir, data, (err) => {
51    if (err) {
52      alternative(stubsPath);
53      return
54    }
55
56    runWireMockOnJustCreatedJar();
57});
58})
59}
60
61function createJarFromNexusSource(stubsPath) {
62  const projectCa = getNpmrcParam(NPMRC_CA_PARAM_NAME);
63  const ca = projectCa !== undefined ? {ca: projectCa} : {};
64  const pathToPackage = MAVEN_REPO + stubsPath;
65
66  console.log("Looking for jar in nexus", pathToPackage);
67  request({
68    method: "GET",
69    uri: pathToPackage,
70    agentOptions: ca
71  }, function(body, err) {
72    if (err) {
73      console.log('Jar downloading status: ' + err.statusCode + ' - ' + err.statusMessage);
74    } else {
75      console.log(body);
76    }
77
78    runWireMockOnJustCreatedJar();
79  }).pipe(fs.createWriteStream(jarDir));
80}
81
82function runWireMockOnJustCreatedJar() {
83  console.log("Running wiremock jar..");
84  extractStubsJar();
85  runWireMock(getParam('port'));
86}
87
88function createBaseStubFolder() {
89  if (!fs.existsSync(dir)){
90    fs.mkdirSync(dir);
91  }
92
93  if (!fs.existsSync(mappingsDir)){
94    fs.mkdirSync(mappingsDir);
95  }
96}
97
98function extractStubsJar() {
99  fs.createReadStream(jarDir)
100    .pipe(unzip.Parse())
101    .on('entry', function (entry) {
102      const fileName = entry.path;
103      if (fileName.endsWith(".json")) {
104        const filenameWithoutFolders = fileName.replace(/^.*[\\\/]/, '');
105        console.log("found", filenameWithoutFolders);
106        entry.pipe(fs.createWriteStream(mappingsDir + '/' + filenameWithoutFolders));
107      } else {
108        entry.autodrain();
109      }
110    });
111}
112
113function cleanStubs(path) {
114  const deleteFolderRecursive = function(path) {
115    if( fs.existsSync(path) ) {
116      fs.readdirSync(path).forEach(function(file,index){
117        const curPath = path + "/" + file;
118        if(fs.lstatSync(curPath).isDirectory()) { // recurse
119          deleteFolderRecursive(curPath);
120        } else {
121          fs.unlinkSync(curPath);
122        }
123      });
124      fs.rmdirSync(path);
125    }
126  };
127
128  deleteFolderRecursive(path);
129}
130
131function runWireMock(port) {
132  const spawn = require('child_process').spawn;
133  spawn('java', ['-jar', './mock/wiremock-standalone-2.14.0.jar', '--root-dir=' + dir, '--port=' + port], { stdio: 'inherit' });
134}
135
136function getUserHome() {
137  return process.env.HOME || process.env.USERPROFILE;
138}
139
140function getParam(key) {
141  for (i = 0; i < process.argv.length; i++) {
142    const val = process.argv[i];
143    const name = val.split('=')[0];
144    if (name === key) {
145      return val.split('=')[1];
146    }
147  }
148
149  console.log("Missing param: " + key);
150  process.exit(-1);
151}
152
153function getNpmrcParam(param) {
154  const paramValue = execSync('npm config get ' + param);
155  return paramValue.toString();
156}
157
Full Screen

publish-package.js

Source: publish-package.js Github

copy
1const fs = require(`fs-extra`)
2const path = require(`path`)
3
4const { promisifiedSpawn } = require(`../utils/promisified-spawn`)
5const { registryUrl } = require(`./verdaccio-config`)
6
7const NPMRCContent = `${registryUrl.replace(
8  /https?:/g,
9  ``
10)}/:_authToken="gatsby-dev"`
11
12const {
13  getMonorepoPackageJsonPath,
14} = require(`../utils/get-monorepo-package-json-path`)
15const { registerCleanupTask } = require(`./cleanup-tasks`)
16
17/**
18 * Edit package.json to:
19 *  - adjust version to temporary one
20 *  - change version selectors for dependencies that
21 *    will be published, to make sure that yarn
22 *    install them in local site
23 */
24const adjustPackageJson = ({
25  monoRepoPackageJsonPath,
26  packageName,
27  versionPostFix,
28  packagesToPublish,
29  ignorePackageJSONChanges,
30  root,
31}) => {
32  // we need to check if package depend on any other package to will be published and
33  // adjust version selector to point to dev version of package so local registry is used
34  // for dependencies.
35
36  const monorepoPKGjsonString = fs.readFileSync(
37    monoRepoPackageJsonPath,
38    `utf-8`
39  )
40  const monorepoPKGjson = JSON.parse(monorepoPKGjsonString)
41
42  monorepoPKGjson.version = `${monorepoPKGjson.version}-dev-${versionPostFix}`
43  packagesToPublish.forEach(packageThatWillBePublished => {
44    if (
45      monorepoPKGjson.dependencies &&
46      monorepoPKGjson.dependencies[packageThatWillBePublished]
47    ) {
48      const currentVersion = JSON.parse(
49        fs.readFileSync(
50          getMonorepoPackageJsonPath({
51            packageName: packageThatWillBePublished,
52            root,
53          }),
54          `utf-8`
55        )
56      ).version
57
58      monorepoPKGjson.dependencies[
59        packageThatWillBePublished
60      ] = `${currentVersion}-dev-${versionPostFix}`
61    }
62  })
63
64  const temporaryMonorepoPKGjsonString = JSON.stringify(monorepoPKGjson)
65
66  const unignorePackageJSONChanges = ignorePackageJSONChanges(packageName, [
67    monorepoPKGjsonString,
68    temporaryMonorepoPKGjsonString,
69  ])
70
71  // change version and dependency versions
72  fs.outputFileSync(monoRepoPackageJsonPath, temporaryMonorepoPKGjsonString)
73
74  return {
75    newPackageVersion: monorepoPKGjson.version,
76    unadjustPackageJson: registerCleanupTask(() => {
77      // restore original package.json
78      fs.outputFileSync(monoRepoPackageJsonPath, monorepoPKGjsonString)
79      unignorePackageJSONChanges()
80    }),
81  }
82}
83
84/**
85 * Anonymous publishing require dummy .npmrc
86 * See https://github.com/verdaccio/verdaccio/issues/212#issuecomment-308578500
87 * This is `npm publish` (as in linked comment) and `yarn publish` requirement.
88 * This is not verdaccio restriction.
89 */
90const createTemporaryNPMRC = ({ pathToPackage }) => {
91  const NPMRCPath = path.join(pathToPackage, `.npmrc`)
92  fs.outputFileSync(NPMRCPath, NPMRCContent)
93
94  return registerCleanupTask(() => {
95    fs.removeSync(NPMRCPath)
96  })
97}
98
99const publishPackage = async ({
100  packageName,
101  packagesToPublish,
102  root,
103  versionPostFix,
104  ignorePackageJSONChanges,
105}) => {
106  const monoRepoPackageJsonPath = getMonorepoPackageJsonPath({
107    packageName,
108    root,
109  })
110
111  const { unadjustPackageJson, newPackageVersion } = adjustPackageJson({
112    monoRepoPackageJsonPath,
113    packageName,
114    root,
115    versionPostFix,
116    packagesToPublish,
117    ignorePackageJSONChanges,
118  })
119
120  const pathToPackage = path.dirname(monoRepoPackageJsonPath)
121
122  const uncreateTemporaryNPMRC = createTemporaryNPMRC({ pathToPackage })
123
124  // npm publish
125  const publishCmd = [
126    `npm`,
127    [`publish`, `--tag`, `gatsby-dev`, `--registry=${registryUrl}`],
128    {
129      cwd: pathToPackage,
130    },
131  ]
132
133  console.log(
134    `Publishing ${packageName}@${newPackageVersion} to local registry`
135  )
136  try {
137    await promisifiedSpawn(publishCmd)
138
139    console.log(
140      `Published ${packageName}@${newPackageVersion} to local registry`
141    )
142  } catch (e) {
143    console.error(`Failed to publish ${packageName}@${newPackageVersion}`, e)
144    process.exit(1)
145  }
146
147  uncreateTemporaryNPMRC()
148  unadjustPackageJson()
149
150  return newPackageVersion
151}
152
153exports.publishPackage = publishPackage
154
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Cypress on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)