I want to test a function. This function also need other function, but this other function will be mocked with jest.
Here is my function
translate(args, cb) {
const transid = args.transid;
const language = args.language;
const defaultValue = args.defaultValue || '';
if (transid === null || transid === '') {
return cb(new Error('Error. Need TransiD'));
}
if (language === null || language === '') {
return cb(new Error('Error. Need language'));
}
return this.translation(transid, language, defaultValue)
.then((res) => {
return cb(null, res);
});
}
That function need function 'translation'. in testing process, i will mocking it.
Here is my function for testing
describe('Translator', () => {
describe('translate', () => {
it('Should return translated value', (done) => {
const args = {
transid: 1,
language: 'EN',
defaultValue: 'defaultValue',
}
const cb = jest.fn((err, res) => {
});
translator.translation = jest.fn((transid, language, defaultValue) => {
// done();
})
translator.translate(args, cb);
done();
});
})
})
I am still confusing how to test that function using Jest and also mocking the required dependencies.
A couple of things I can see:
done function by returning the Promise chain, which Jest will use to determine when a test is complete.Here's how the test might look:
describe('Translator', () => {
describe('translate', () => {
it('Should return translated value', () => {
const args = {
transid: 1,
language: 'EN',
defaultValue: 'defaultValue',
}
const cb = jest.fn();
const res = {};
translator.translation = jest.fn()
.mockReturnValue(Promise.resolve(res));
return translator.translate(args, cb)
.then(() => {
expect(translator.translation).toHaveBeenCalledTimes(1);
expect(translator.translation)
.toHaveBeenCalledWith(1, 'EN', 'defaultValue');
expect(cb).toHaveBeenCalledTimes(1);
expect(cb).toHaveBeenCalledWith(null, res);
});
});
})
})