mfncooper / mockery

Simplifying the use of mocks with Node.js
Other
1.1k stars 60 forks source link

registerMock() does not work when code is ran with jest? #66

Closed kairun closed 7 years ago

kairun commented 7 years ago

Below code does not look work at all, I do not think I've made any mistakes here, but console still logs out the return from from original aws-sdk require call, not newly mocked {}

test.spec.js

require('jest');
const mockery = require('mockery');

describe('test', () => {
  beforeAll(() => {
    mockery.enable({
      warnOnReplace: false,
      warnOnUnregistered: false
    });
    mockery.registerMock('aws-sdk', {});
    const aws = require('aws-sdk');
    console.log(aws);
  });

  it('', () => {
    expect(true).toBeTruthy();
  });
});

strangely, this does work if

  1. I do this for 'fs' module, not the 'aws-sdk' (which isn't native module of node)
  2. Run this just with a node after stripping all jest related code (which means running the test with jest makes this code fail)
kairun commented 7 years ago

For anyone who is taking same path as me (who are migrating from Mocha & Mockery & Sinon & Chai towards Jest),

Jest offers their native version of require mocks, which removes any inconsistent mockery behaviours in the context of Jest,

such as:

  1. not restoring fs module if mocked via mockery
  2. not mocking 3rd party npm modules properly
wahengchang commented 6 years ago

jest does not support mocking non-existed file, for example different env getting different config.json file, and all config.json is needed testing on all env (for 100% coverage).

not sure if anyone meet the problem