diff --git a/test/test-utils.test.js b/test/test-utils.test.js index a1bd8d46b2a..aecac4d40af 100644 --- a/test/test-utils.test.js +++ b/test/test-utils.test.js @@ -1,6 +1,8 @@ "use strict"; -const { extractHash } = require("./testUtils"); +const { extractHash, appendDataIfFileExists } = require("./testUtils"); +const { writeFileSync, unlinkSync, readFileSync } = require("fs"); +const { resolve } = require("path"); describe("extractHash functionality", () => { it("should throw Error if there is empty string", () => { @@ -101,3 +103,29 @@ Child ${config2Name}: expect(hashInfo.config[1]).toEqual({ name: config2Name, hash: config2Hash }); }); }); + +describe("appendFile functionality", () => { + describe("positive test-cases", () => { + const junkFile = resolve(__dirname, "junkFile.js"); + + beforeEach(() => { + writeFileSync(junkFile, ""); + }); + afterEach(() => { + unlinkSync(junkFile); + }); + it("should append data to file if file exists", () => { + const expectedData = "//junk comment"; + appendDataIfFileExists(__dirname, junkFile, expectedData); + const actualData = readFileSync(junkFile).toString(); + + expect(actualData).toBe(expectedData); + }); + }); + + describe("negative test-cases", () => { + it("should throw error if file does not exist", () => { + expect(() => appendDataIfFileExists(__dirname, "does-not-exist.js", "junk data")).toThrowError(); + }); + }); +}); diff --git a/test/testUtils.js b/test/testUtils.js index e425ea3dd0a..64da8ac336a 100644 --- a/test/testUtils.js +++ b/test/testUtils.js @@ -148,4 +148,23 @@ function extractHash(stdout) { return hashInfo; } -module.exports = { run, runWatch, extractHash, extractSummary }; +/*eslint valid-jsdoc: ["error", { "requireReturn": false }]*/ +/** + * + * @param {*} testCase - testCase directory + * @param {*} file - file relative to testCase + * @param {*} data - data to append + * @throws - throw an Error if file does not exist + */ +function appendDataIfFileExists(testCase, file, data) { + const { existsSync, appendFileSync } = require("fs"); + + const filePath = path.resolve(testCase, file); + if (existsSync(filePath)) { + appendFileSync(filePath, data); + } else { + throw new Error(`Oops! ${filePath} does not exist!`); + } +} + +module.exports = { run, runWatch, extractHash, extractSummary, appendDataIfFileExists };