-
-
Notifications
You must be signed in to change notification settings - Fork 771
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add documentation for how to stub ES6 module dependencies #1358
Comments
To contribute to my own question, the only way I found this to work is by using import test from 'ava';
import sinon from 'sinon';
import moment from 'moment';
import createReservation from '../../../src/mutators/createReservation';
test('throws an error if the event is in the past', async (t) => {
const parameters: any = {};
const context: any = {
session: {
userId: 1
}
};
const stub = sinon.stub().returns({
date: moment().format('YYYY-MM-DD'),
time: moment(new Date().getTime() - 1000 * 60).format('HH:mm')
});
createReservation.__Rewire__('getEventByEventId', stub);
await t.throws(createReservation(context), 'Cannot create a reservation for a past event.');
}); This solution is far from ideal, though. For one, it breaks the Flow type annotations. |
One way to improve a DX would be to provide an ability to define a getter method when stubbing an object, e.g. const stub = sinon.stub(createReservation, '__Rewire__', 'getEventByEventId'); which would be equivalent to: const stub = sinon.stub();
createReservation.__Rewire__('getEventByEventId', stub); |
I've solved this locally by creating an ad-hoc helper for rewiring the dependencies: const rewire = (module: any, methodName: string, method) => {
module.__Rewire__(methodName, method);
return method;
}; which I am then using like this: rewire(createReservation, 'getEventByEventId', sinon.stub())
.returns({
date: moment().format('YYYY-MM-DD'),
time: moment(new Date().getTime() - 1000 * 60).format('HH:mm')
}); |
Duplicate of #1121 |
proxyquire looks like a good choice for this case @gajus , as the function is imported as a module |
This may be old news, but I do this import * as myDependency from './some/other/file'
beforeEach(function () {
this.mySpy = sinon.spy(myDependency, 'default');
}); |
It's a bad idea to use |
We even have a guide on How to use Link Seams with CommonJS. |
It is a common use case to mock ES modules.
e.g. I have a module that imports
getEventByEventId
In my test I want to mock
getEventByEventId
, e.g.The text was updated successfully, but these errors were encountered: