Skip to content

Commit e9e1dcb

Browse files
hemal7735evenstensberg
authored andcommittedFeb 5, 2019
feat: add test-util to append data to file
1 parent 8357dbc commit e9e1dcb

File tree

2 files changed

+49
-2
lines changed

2 files changed

+49
-2
lines changed
 

‎test/test-utils.test.js

+29-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
"use strict";
22

3-
const { extractHash } = require("./testUtils");
3+
const { extractHash, appendDataIfFileExists } = require("./testUtils");
4+
const { writeFileSync, unlinkSync, readFileSync } = require("fs");
5+
const { resolve } = require("path");
46

57
describe("extractHash functionality", () => {
68
it("should throw Error if there is empty string", () => {
@@ -101,3 +103,29 @@ Child ${config2Name}:
101103
expect(hashInfo.config[1]).toEqual({ name: config2Name, hash: config2Hash });
102104
});
103105
});
106+
107+
describe("appendFile functionality", () => {
108+
describe("positive test-cases", () => {
109+
const junkFile = resolve(__dirname, "junkFile.js");
110+
111+
beforeEach(() => {
112+
writeFileSync(junkFile, "");
113+
});
114+
afterEach(() => {
115+
unlinkSync(junkFile);
116+
});
117+
it("should append data to file if file exists", () => {
118+
const expectedData = "//junk comment";
119+
appendDataIfFileExists(__dirname, junkFile, expectedData);
120+
const actualData = readFileSync(junkFile).toString();
121+
122+
expect(actualData).toBe(expectedData);
123+
});
124+
});
125+
126+
describe("negative test-cases", () => {
127+
it("should throw error if file does not exist", () => {
128+
expect(() => appendDataIfFileExists(__dirname, "does-not-exist.js", "junk data")).toThrowError();
129+
});
130+
});
131+
});

‎test/testUtils.js

+20-1
Original file line numberDiff line numberDiff line change
@@ -148,4 +148,23 @@ function extractHash(stdout) {
148148
return hashInfo;
149149
}
150150

151-
module.exports = { run, runWatch, extractHash, extractSummary };
151+
/*eslint valid-jsdoc: ["error", { "requireReturn": false }]*/
152+
/**
153+
*
154+
* @param {*} testCase - testCase directory
155+
* @param {*} file - file relative to testCase
156+
* @param {*} data - data to append
157+
* @throws - throw an Error if file does not exist
158+
*/
159+
function appendDataIfFileExists(testCase, file, data) {
160+
const { existsSync, appendFileSync } = require("fs");
161+
162+
const filePath = path.resolve(testCase, file);
163+
if (existsSync(filePath)) {
164+
appendFileSync(filePath, data);
165+
} else {
166+
throw new Error(`Oops! ${filePath} does not exist!`);
167+
}
168+
}
169+
170+
module.exports = { run, runWatch, extractHash, extractSummary, appendDataIfFileExists };

0 commit comments

Comments
 (0)
Please sign in to comment.