Skip to content

Commit 6a01337

Browse files
committed
test: improve test coverage for watcher
1 parent a513983 commit 6a01337

1 file changed

Lines changed: 24 additions & 1 deletion

File tree

‎test/unit/server/watcher.test.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,8 @@ describe('watcher.ts unit tests', () => {
5555

5656
mockDirectoryWatcher = {
5757
on: jest.fn().mockReturnThis(),
58-
close: jest.fn(),
58+
close: jest.fn().mockResolvedValue(undefined),
59+
unwatch: jest.fn(),
5960
} as unknown as FSWatcher;
6061
(chokidar.watch as jest.Mock).mockReturnValue(mockDirectoryWatcher);
6162

@@ -197,6 +198,11 @@ describe('watcher.ts unit tests', () => {
197198
expect(chokidar.watch).not.toHaveBeenCalled();
198199
});
199200

201+
it('should log error if WebSocket message payload is invalid JSON', () => {
202+
onClientMessage('{invalid-json');
203+
expect(logger.error).toHaveBeenCalledWith('🚫 Error parsing WebSocket message:', expect.any(Error));
204+
});
205+
200206
it('should log error if content watcher encounters an error', () => {
201207
(chokidar.watch as jest.Mock).mockReturnValueOnce(mockContentWatcher);
202208
onClientMessage(JSON.stringify({ type: 'watch-file', filePath: '/mock/file.md' }));
@@ -246,6 +252,23 @@ describe('watcher.ts unit tests', () => {
246252
expect(logger.error).toHaveBeenCalledWith('🚫 Error watching directory:', expect.any(Error));
247253
expect(logger.error).toHaveBeenCalledWith('Livereload will be disabled');
248254
});
255+
256+
it('should close directory watcher and log EMFILE guidance on watcher error event', async () => {
257+
const onErrorCallback = (mockDirectoryWatcher.on as jest.Mock).mock.calls.find(call => call[0] === 'error')[1];
258+
const error = Object.assign(new Error('Too many open files'), { code: 'EMFILE' });
259+
260+
onErrorCallback(error);
261+
await Promise.resolve();
262+
263+
expect(mockDirectoryWatcher.unwatch).toHaveBeenCalledWith('/mock/directory');
264+
expect(mockDirectoryWatcher.close).toHaveBeenCalled();
265+
expect(logger.log).toHaveBeenCalledWith('Livereload', 'Directory watcher closed');
266+
expect(logger.error).toHaveBeenCalledWith('🚫 Error watching directory:', error);
267+
expect(logger.error).toHaveBeenCalledWith('Livereload will be disabled');
268+
expect(logger.error).toHaveBeenCalledWith(
269+
'This error is likely caused by too many open files. Try increasing the ulimit.',
270+
);
271+
});
249272
});
250273

251274
describe('chokidar ignored option', () => {

0 commit comments

Comments
 (0)