Skip to content

Instantly share code, notes, and snippets.

@yogeshlonkar
Last active July 3, 2019 08:51
Show Gist options
  • Save yogeshlonkar/814017e1922f2be7caaa2a71f80d35ab to your computer and use it in GitHub Desktop.
Save yogeshlonkar/814017e1922f2be7caaa2a71f80d35ab to your computer and use it in GitHub Desktop.
Smart ES6 class mock, Create method proxies on module for easier mocking
class Abc {
func1() {
return 'This is function 1'
}
func2() {
return 2;
}
func3() {
return Promise.resolve('three');
}
}
module.exports = Abc;
const IgnoreFunc = ['constructor', '__defineGetter__', '__defineSetter__', '__lookupSetter__', '__lookupGetter__', 'default', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'];
const createMethodProxies = mockedModule => {
if (mockedModule && mockedModule.mock) {
for (const instance of mockedModule.mock.instances) {
for (const method in instance) {
if (!IgnoreFunc.includes(method) && !mockedModule[method]) {
mockedModule[method] = {};
for (const proxyMethod of ['mockClear', 'mockReset', 'mockRestore', 'mockImplementation', 'mockImplementationOnce', 'mockName', 'mockReturnThis', 'mockReturnValue', 'mockReturnValueOnce', 'mockResolvedValue', 'mockResolvedValueOnce', 'mockRejectedValue', 'mockRejectedValueOnce']) {
mockedModule[method][proxyMethod] = (...args) => {
for (const instance of mockedModule.mock.instances) {
instance[method][proxyMethod](...args);
}
};
}
}
}
}
}
};
module.exports = createMethodProxies;
const Abc = require('./Abc');
class Xyz {
constructor() {
this.abc = new Abc();
}
funcToTest1() {
const result = 'Xyz ->' + this.abc.func1();
return result;
}
async funcToTest2() {
const result = 'Xyz ->' + await this.abc.func2();
return result;
}
async funcToTest3() {
const result = 'Xyz ->' + await this.abc.func3();
return result;
}
}
module.exports = Xyz;
const createMethodProxies = require('./createMethodProxies');
const Abc = require('./Abc');
const Xyz = require('./Xyz');
jest.mock('./Abc');
describe('Xyz', () => {
let xyz;
beforeEach(() => {
xyz = new Xyz();
createMethodProxies(Abc);
})
it('should return correct value on funcToTest1', () => {
Abc.func1.mockReturnValueOnce('test123');
const actual = xyz.funcToTest1();
expect(actual).toEqual('Xyz ->test123');
});
it('should return correct value on funcToTest2', async () => {
Abc.func2.mockReturnValueOnce(Promise.resolve(444));
const actual = await xyz.funcToTest2();
expect(actual).toEqual('Xyz ->444');
});
it('should return correct value on funcToTest3', async () => {
Abc.func3.mockReturnValueOnce(Promise.resolve('four'));
const actual = await xyz.funcToTest3();
expect(actual).toEqual('Xyz ->four');
});
});
@yogeshlonkar
Copy link
Author

Abc.mock.instance[x].method.mockReturnValueOnce do Abc.mockReturnValueOnce

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment