Skip to content

Instantly share code, notes, and snippets.

@edjeordjian
Created March 13, 2022 16:29
Show Gist options
  • Save edjeordjian/771e6fbbb32503bc9b2819380e99c1a9 to your computer and use it in GitHub Desktop.
Save edjeordjian/771e6fbbb32503bc9b2819380e99c1a9 to your computer and use it in GitHub Desktop.
Examples for mocking in Node with Rewire Library
// [Mock a class]
// (when calling myFile.myMethod(), ClassIWantToMockInMyFie will be replaced by MyMockClass)
const myFile = rewire("../src/myFile");
myFile.__set__( {
'ClassIWantToMockInMyFie': MyMockClass
} );
// [Mock a method]
// (when calling myFile.myMethod() or myFile.myOtherMethod(), myMethod behavior will be replaced with the defined return value)
const myFile = rewire("../src/myFile");
myFile.__set__('myMethod', () => 'theValueThatTheMethodShouldReturn');
// [Mock a method of a dependency]
// Example: mocking bcrypto hashSync and genSaltSync
const utilsFile = rewire("../src/others/utils");
utilsFile.__set__('bcrypt.genSaltSync', () => '123');
utilsFile.__set__('bcrypt.hashSync', () => '123');
assert.strictEqual( utilsFile.getBcryptOf("a") , '123');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment