diff --git a/src/emulation/promises.ts b/src/emulation/promises.ts index 6a6be1a3..c6d1e211 100644 --- a/src/emulation/promises.ts +++ b/src/emulation/promises.ts @@ -951,9 +951,10 @@ export function watch( options?: fs.WatchOptions | string ): AsyncIterable> | AsyncIterable>; export function watch(this: V_Context, filename: fs.PathLike, options: fs.WatchOptions | string = {}): AsyncIterable> { + const context = this; return { [Symbol.asyncIterator](): AsyncIterator> { - const watcher = new FSWatcher(this, filename.toString(), typeof options !== 'string' ? options : { encoding: options as BufferEncoding | 'buffer' }); + const watcher = new FSWatcher(context, filename.toString(), typeof options !== 'string' ? options : { encoding: options as BufferEncoding | 'buffer' }); // A queue to hold change events, since we need to resolve them in the async iterator const eventQueue: ((value: IteratorResult>) => void)[] = []; diff --git a/tests/common/context.test.ts b/tests/common/context.test.ts index 5f782fff..35684adf 100644 --- a/tests/common/context.test.ts +++ b/tests/common/context.test.ts @@ -16,4 +16,21 @@ suite('Context', () => { test('break-out fails', () => { assert.deepEqual(c_fs.readdirSync('/../../'), ['example.txt']); }); + + test('watch should consider context', async () => { + let lastFile: string, + events = 0; + const watcher = c_fs.promises.watch('/', { recursive: true }); + + (async () => { + for await (const event of watcher) { + lastFile = event.filename!; + if (++events == 2) return; + } + })(); + await c_fs.promises.writeFile('/xpto.txt', 'in real root'); + assert.strictEqual(lastFile!, 'xpto.txt'); + await c_fs.promises.unlink('/xpto.txt'); + assert.strictEqual(lastFile, 'xpto.txt'); + }); });