Skip to content

Commit

Permalink
Add file creation tests
Browse files Browse the repository at this point in the history
Signed-off-by: Marcos Candeia <[email protected]>
  • Loading branch information
mcandeia committed Nov 20, 2024
1 parent b4f62b7 commit aa4b6bf
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/emulation/watchers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type * as fs from 'node:fs';
import { ErrnoError } from '../error.js';
import { isStatsEqual, type Stats } from '../stats.js';
import { normalizePath } from '../utils.js';
import { dirname } from './path.js';
import { basename, dirname } from './path.js';
import { statSync } from './sync.js';

/**
Expand Down Expand Up @@ -175,16 +175,17 @@ export function emitChange(eventType: fs.WatchEventType, filename: string) {
// Notify watchers on the specific file
if (watchers.has(normalizedFilename)) {
for (const watcher of watchers.get(normalizedFilename)!) {
watcher.emit('change', eventType, filename.substring(normalizedFilename.length));
watcher.emit('change', eventType, basename(filename));
}
}

// Notify watchers on parent directories if they are watching recursively
let parent = dirname(normalizedFilename);
do {
const offset = parent == '/' ? 0 : 1; // used to remove the leading slash
if (watchers.has(parent)) {
for (const watcher of watchers.get(parent)!) {
watcher.emit('change', eventType, filename.substring(parent.length));
watcher.emit('change', eventType, filename.substring(parent.length + offset));
}
}
normalizedFilename = parent;
Expand Down
21 changes: 21 additions & 0 deletions tests/fs/watch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,27 @@ suite('Watch Features', () => {
resolve();
})();

await fs.promises.unlink(tempFile);
await promise;
});
test('fs.promises.watch should detect file creations recursively', async () => {
const rootDir = '/';
const subDir = `${testDir}sub-dir`;
const tempFile = `${subDir}/tempFile.txt`;
await fs.promises.mkdir(subDir);
const watcher = fs.promises.watch(rootDir);

await fs.promises.writeFile(tempFile, 'Temporary content');
const { promise, resolve } = Promise.withResolvers<void>();
(async () => {
for await (const event of watcher) {
assert.equal(event.eventType, 'rename');
assert.equal(event.filename, tempFile.substring(rootDir.length));
break;
}
resolve();
})();

await fs.promises.unlink(tempFile);
await promise;
});
Expand Down

0 comments on commit aa4b6bf

Please sign in to comment.