Skip to content

Instantly share code, notes, and snippets.

@skypesky
Last active July 19, 2023 11:34
Show Gist options
  • Save skypesky/3c45af2ee5a641be967b968392897e57 to your computer and use it in GitHub Desktop.
Save skypesky/3c45af2ee5a641be967b968392897e57 to your computer and use it in GitHub Desktop.
mock 写法大全

How to mock deeply nested objects?

const states = require('states');

jest.mock('states', () => ({ auditLog: { find: jest.fn(() => []) } }));

expect(states.auditLog.find).toBeCalled();

Only part of the mock module

const { isEmpty } = require('lodash');

jest.mock('lodash', () => ({
  ...jest.requireActual('lodash'),
  // Only mock isEmpty function
  isEmpty: jest.fn(),
}));

expect(isEmpty).toBeCalled();

Only mock class constructors and methods

// wait test codes
class Coder {
  async helloWorld() {
    const StreamZip = require('node-stream-zip');
    const zip = new StreamZip.async({ file: blockletZipPath });
    await zip.extract(null, join(this.blockletRestoreDir, 'blocklets'));
    await zip.close();
    removeSync(blockletZipPath);
  }
}

// test codes
const StreamZip = require('node-stream-zip');
jest.mock('node-stream-zip');

test('should be work', async () => {
  const coder = new Coder();
  await coder.hellWorld();

  expect(StreamZip.async).toBeCalledWith({
    file: blockletZipPath,
  });
  expect(StreamZip.async.prototype.extract).toBeCalled();
  expect(StreamZip.async.prototype.close).toBeCalled();
});

Match only part of the object

expect({ name: 'skypesky', email: 'xxx' }).toEqual(expect.objectContaining({ name: 'skypesky' }));

Mock debug.js

declare global {
  var debugMock: jest.Mock<any, any>;
}

jest.mock('debug', () => {
  // @ts-ignore
  global.debugMock = jest.fn();
  // @ts-ignore
  return () => global.debugMock;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment