Skip to content

Commit 658560e

Browse files
refackjasnell
authored andcommitted
test,fs: test fs.watch for filename
PR-URL: #13411 Refs: #13385 Refs: #13248 Refs: #13377 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 5644dd7 commit 658560e

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

test/parallel/test-fs-watch.js

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
'use strict';
2+
const common = require('../common');
3+
4+
// tests if `filename` is provided to watcher on supported platforms
5+
6+
const fs = require('fs');
7+
const assert = require('assert');
8+
const { join } = require('path');
9+
10+
class WatchTestCase {
11+
constructor(shouldInclude, dirName, fileName, field) {
12+
this.dirName = dirName;
13+
this.fileName = fileName;
14+
this.field = field;
15+
this.shouldSkip = !shouldInclude;
16+
}
17+
get dirPath() { return join(common.tmpDir, this.dirName); }
18+
get filePath() { return join(this.dirPath, this.fileName); }
19+
}
20+
21+
const cases = [
22+
// Watch on a directory should callback with a filename on supported systems
23+
new WatchTestCase(
24+
common.isLinux || common.isOSX || common.isWindows || common.isAix,
25+
'watch1',
26+
'foo',
27+
'filePath'
28+
),
29+
// Watch on a file should callback with a filename on supported systems
30+
new WatchTestCase(
31+
common.isLinux || common.isOSX || common.isWindows,
32+
'watch2',
33+
'bar',
34+
'dirPath'
35+
)
36+
];
37+
38+
common.refreshTmpDir();
39+
40+
for (const testCase of cases) {
41+
if (testCase.shouldSkip) continue;
42+
fs.mkdirSync(testCase.dirPath);
43+
// long content so it's actually flushed.
44+
const content1 = Date.now() + testCase.fileName.toLowerCase().repeat(1e4);
45+
fs.writeFileSync(testCase.filePath, content1);
46+
47+
let interval;
48+
const watcher = fs.watch(testCase[testCase.field]);
49+
watcher.on('error', (err) => {
50+
if (interval) {
51+
clearInterval(interval);
52+
interval = null;
53+
}
54+
assert.fail(err);
55+
});
56+
watcher.on('change', common.mustCall(function(eventType, argFilename) {
57+
if (interval) {
58+
clearInterval(interval);
59+
interval = null;
60+
}
61+
if (common.isOSX)
62+
assert.strictEqual(['rename', 'change'].includes(eventType), true);
63+
else
64+
assert.strictEqual(eventType, 'change');
65+
assert.strictEqual(argFilename, testCase.fileName);
66+
67+
// end of test case
68+
watcher.close();
69+
}));
70+
71+
// long content so it's actually flushed. toUpperCase so there's real change.
72+
const content2 = Date.now() + testCase.fileName.toUpperCase().repeat(1e4);
73+
interval = setInterval(() => {
74+
fs.writeFileSync(testCase.filePath, '');
75+
fs.writeFileSync(testCase.filePath, content2);
76+
}, 100);
77+
}

0 commit comments

Comments
 (0)