I would like to test a file with testdouble
. However, I have a method helperFunc
that I am unsure how to mock in the file here. If it were a class method, I would use MyClass.prototype.method = td.func()
but here I tried using const helperFunc = td.func('helperFunc')
without any luck. I also tried using td.replace
but it threw an error.
Is it possible to replace this helperFunc
with a fake function i.e. td.func()
?
Here is the file I want to test:
MyClass.js
const helperFunc = (data) => {
return new Promise((resolve, reject) => {
let result = // Work with 3rd party package
resolve(result)
})
}
class MyClass {
method(data, callback) {
return helperFunc(data).then(result => {
return callback(result);
}).catch(err => callback(null, err));
}
}
module.exports = MyClass;
Here is my test file so far
testfile.test.js
const { expect } = require('chai');
const td = require('testdouble');
describe('my test', function () {
let MyClass;
let classInstance;
let finalResult;
before(function () {
MyClass = require('../MyClass.js');
const helperFunc = td.func('helperFunc');
td.when(helperFunc(td.matchers.anything)).thenReturn('fakeData');
classInstance = new MyClass();
const testData = 'testdata';
const callback = (returnData, err) => {
finalResult = returnData;
}
classInstance.method(testData, callback);
})
it('should return fake data', function() {
expect(finalResult).to.equal('fakeData');
})
})