How to use fs.readJson 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.

init-command.test.js

Source: init-command.test.js Github

copy
1"use strict";
2
3const fs = require("fs-extra");
4const path = require("path");
5const tempy = require("tempy");
6
7// helpers
8const initFixture = require("@lerna-test/init-fixture")(__dirname);
9
10// file under test
11const lernaInit = require("@lerna-test/command-runner")(require("../command"));
12
13describe("InitCommand", () => {
14  const lernaVersion = "__TEST_VERSION__";
15
16  describe("in an empty directory", () => {
17    it("initializes git repo with lerna files", async () => {
18      const testDir = tempy.directory();
19
20      await lernaInit(testDir)();
21
22      const [lernaJson, pkgJson, packagesDirExists, gitDirExists] = await Promise.all([
23        fs.readJSON(path.join(testDir, "lerna.json")),
24        fs.readJSON(path.join(testDir, "package.json")),
25        fs.exists(path.join(testDir, "packages")),
26        fs.exists(path.join(testDir, ".git")),
27      ]);
28
29      expect(lernaJson).toMatchObject({
30        packages: ["packages/*"],
31        version: "0.0.0",
32      });
33      expect(pkgJson).toMatchObject({
34        devDependencies: {
35          lerna: `^${lernaVersion}`,
36        },
37      });
38      expect(packagesDirExists).toBe(true);
39      expect(gitDirExists).toBe(true);
40    });
41
42    it("initializes git repo with lerna files in independent mode", async () => {
43      const testDir = tempy.directory();
44
45      await lernaInit(testDir)("--independent");
46
47      expect(await fs.readJSON(path.join(testDir, "lerna.json"))).toHaveProperty("version", "independent");
48    });
49
50    describe("with --exact", () => {
51      it("uses exact version when adding lerna dependency", async () => {
52        const testDir = tempy.directory();
53
54        await lernaInit(testDir)("--exact");
55
56        expect(await fs.readJSON(path.join(testDir, "package.json"))).toMatchObject({
57          devDependencies: {
58            lerna: lernaVersion,
59          },
60        });
61      });
62
63      it("sets lerna.json command.init.exact to true", async () => {
64        const testDir = tempy.directory();
65
66        await lernaInit(testDir)("--exact");
67
68        expect(await fs.readJSON(path.join(testDir, "lerna.json"))).toMatchObject({
69          command: {
70            init: {
71              exact: true,
72            },
73          },
74        });
75      });
76    });
77  });
78
79  describe("in a subdirectory of a git repo", () => {
80    it("creates lerna files", async () => {
81      const dir = await initFixture("empty");
82      const testDir = path.join(dir, "subdir");
83
84      await fs.ensureDir(testDir);
85      await lernaInit(testDir)();
86
87      const [lernaJson, pkgJson, packagesDirExists] = await Promise.all([
88        fs.readJSON(path.join(testDir, "lerna.json")),
89        fs.readJSON(path.join(testDir, "package.json")),
90        fs.exists(path.join(testDir, "packages")),
91      ]);
92
93      expect(lernaJson).toMatchObject({
94        packages: ["packages/*"],
95        version: "0.0.0",
96      });
97      expect(pkgJson).toMatchObject({
98        devDependencies: {
99          lerna: `^${lernaVersion}`,
100        },
101      });
102      expect(packagesDirExists).toBe(true);
103    });
104  });
105
106  describe("when package.json exists", () => {
107    it("adds lerna to sorted devDependencies", async () => {
108      const testDir = await initFixture("has-package");
109      const pkgJsonPath = path.join(testDir, "package.json");
110
111      await fs.outputJSON(pkgJsonPath, {
112        devDependencies: {
113          alpha: "first",
114          omega: "last",
115        },
116      });
117
118      await lernaInit(testDir)();
119
120      expect(await fs.readJSON(pkgJsonPath)).toMatchObject({
121        devDependencies: {
122          alpha: "first",
123          lerna: `^${lernaVersion}`,
124          omega: "last",
125        },
126      });
127    });
128
129    it("updates existing lerna in devDependencies", async () => {
130      const testDir = await initFixture("has-package");
131      const pkgJsonPath = path.join(testDir, "package.json");
132
133      await fs.outputJSON(pkgJsonPath, {
134        dependencies: {
135          alpha: "first",
136          omega: "last",
137        },
138        devDependencies: {
139          lerna: "0.1.100",
140        },
141      });
142
143      await lernaInit(testDir)();
144
145      expect(await fs.readJSON(pkgJsonPath)).toMatchObject({
146        dependencies: {
147          alpha: "first",
148          omega: "last",
149        },
150        devDependencies: {
151          lerna: `^${lernaVersion}`,
152        },
153      });
154    });
155
156    it("updates existing lerna in sorted dependencies", async () => {
157      const testDir = await initFixture("has-package");
158      const pkgJsonPath = path.join(testDir, "package.json");
159
160      await fs.outputJSON(pkgJsonPath, {
161        dependencies: {
162          alpha: "first",
163          lerna: "0.1.100",
164          omega: "last",
165        },
166      });
167
168      await lernaInit(testDir)();
169
170      expect(await fs.readJSON(pkgJsonPath)).toMatchObject({
171        dependencies: {
172          alpha: "first",
173          lerna: `^${lernaVersion}`,
174          omega: "last",
175        },
176      });
177    });
178  });
179
180  describe("when lerna.json exists", () => {
181    it("deletes lerna property if found", async () => {
182      const testDir = await initFixture("has-lerna");
183      const lernaJsonPath = path.join(testDir, "lerna.json");
184
185      await fs.outputJSON(lernaJsonPath, {
186        lerna: "0.1.100",
187        version: "1.2.3",
188      });
189
190      await lernaInit(testDir)();
191
192      expect(await fs.readJSON(lernaJsonPath)).toEqual({
193        packages: ["packages/*"],
194        version: "1.2.3",
195      });
196    });
197
198    it("creates package directories when glob is configured", async () => {
199      const testDir = await initFixture("has-lerna");
200      const lernaJsonPath = path.join(testDir, "lerna.json");
201
202      await fs.outputJSON(lernaJsonPath, {
203        packages: ["modules/*"],
204      });
205
206      await lernaInit(testDir)();
207
208      expect(await fs.exists(path.join(testDir, "modules"))).toBe(true);
209    });
210  });
211
212  describe("when re-initializing with --exact", () => {
213    it("sets lerna.json command.init.exact to true", async () => {
214      const testDir = await initFixture("updates");
215      const lernaJsonPath = path.join(testDir, "lerna.json");
216      const pkgJsonPath = path.join(testDir, "package.json");
217
218      await fs.outputJSON(lernaJsonPath, {
219        lerna: "0.1.100",
220        commands: {
221          bootstrap: {
222            hoist: true,
223          },
224        },
225        version: "1.2.3",
226      });
227      await fs.outputJSON(pkgJsonPath, {
228        devDependencies: {
229          lerna: lernaVersion,
230        },
231      });
232
233      await lernaInit(testDir)("--exact");
234
235      expect(await fs.readJSON(lernaJsonPath)).toEqual({
236        command: {
237          bootstrap: {
238            hoist: true,
239          },
240          init: {
241            exact: true,
242          },
243        },
244        packages: ["packages/*"],
245        version: "1.2.3",
246      });
247    });
248  });
249});
250
Full Screen

product-repo.js

Source: product-repo.js Github

copy
1import fs from 'fs-extra'
2import {fileURLToPath} from 'url';
3
4const url = new URL('../data/products.json', import.meta.url);
5const filePath = fileURLToPath(url);
6
7class ProductRepo {
8    async getProducts() {
9        return await fs.readJson(filePath)
10    }
11
12    async getProduct(pid) {
13        const products = await fs.readJson(filePath)
14        return products.find(pr => pr.pid == pid)
15    }
16
17    async addProduct(newProduct) {
18        const products = await fs.readJson(filePath)
19        products.push(newProduct)
20        return await fs.writeJson(filePath, products)
21    }
22
23    async updateProduct(updatedProduct) {
24        const products = await fs.readJson(filePath)
25        const index = products.findIndex(product => product.pid == updatedProduct.pid)
26        if (index >= 0) {
27            console.log(index)
28            products[index] = updatedProduct
29            return await fs.writeJson(filePath, products)
30        }
31        return null
32    }
33
34    async deleteProduct(pid) {
35        const products = await fs.readJson(filePath)
36        const filteredProducts = products.filter(pr => pr.pid != pid)
37        return await fs.writeJson(filePath, filteredProducts)
38    }
39
40    async deleteAllProducts() {
41        return await fs.writeJson(filePath, [])
42    }
43
44    async getStatistics() {
45        const products = await fs.readJson(filePath)
46        const totalProduct = products.length
47        const totalPrice = products.reduce((num, sum) => +num + +sum.price, 0)
48        return {
49            "totalNumberOfProducts": totalProduct,
50            "totalPrice": totalPrice
51        }
52    }
53
54    async getTopExpensiveProducts(limit) {
55        const products = await fs.readJson(filePath)
56        const topThree = products.sort((a, b) => b.price - a.price).splice(0, limit)
57        return topThree
58    }
59}
60
61export default new ProductRepo()
62
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)