Skip to content

jest.Mocked doesn't deal with declaration merging #34889

@lifeiscontent

Description

@lifeiscontent

@NoHomey @jwbay @asvetliakov @alexjoverm @epicallan @ikatyang @wsmd @JamieMason @douglasduteil @ahnpnl @JoshuaKGoldberg @UselessPickles @r3nya @Hotell @sebald @andys8 @antoinebrault

when trying to mock the fs library the declarations don't merge, not sure if this is due to bad declarations in the Node.js definition or jest

here's my example:

import base from './base';
import _fs from 'fs';

jest.mock('fs');

const fs: jest.Mocked<typeof _fs> = _fs as any;

class ErrnoException extends Error {
  constructor(public code: string, public message = '') {
    super(message);
    Object.setPrototypeOf(this, ErrnoException.prototype);
  }
}

describe('base', () => {
  describe('read', () => {
    describe('when file exists', () => {
      beforeEach(() => {
        // @ts-ignore until fixed
        fs.readFile.mockImplementation((_path, options, callback) => {
          if (typeof options === 'string' && options === 'utf8') {
            callback(
              null,
              Buffer.from(JSON.stringify({ phone: '5555555555' }), options)
            );
          }
        });
      });

      it('reads the file', async () => {
        expect(
          await base.read<{ phone: '5555555555' }>('users', '5555555555')
        ).toEqual({
          phone: '5555555555'
        });
        expect(fs.readFile).toHaveBeenCalled();
      });
    });
    describe('when file does not exist', () => {
      beforeEach(() => {
        // @ts-ignore until fixed
        fs.readFile.mockImplementation((_path, _options, callback) => {
          callback(new ErrnoException('ENOENT'));
        });
      });

      it('throws an error', () => {
        expect(base.read('users', '5555555555')).rejects.toEqual(
          expect.objectContaining({ code: 'ENOENT' })
        );
        expect(fs.readFile).toHaveBeenCalled();
      });
    });
  });
});

please let me know if there's something I can do on my end, I'd make a PR myself but I'm unsure how to solve the problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions