Skip to content
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

[Feature request] stub emits #1045

Closed
perrin4869 opened this issue May 14, 2016 · 4 comments
Closed

[Feature request] stub emits #1045

perrin4869 opened this issue May 14, 2016 · 4 comments

Comments

@perrin4869
Copy link
Contributor

In addition to returns, yields, throws, etc, when stubbing a method, i.e., stub(obj, 'method'), it would be useful to specify an emits behavior, such as, for example:

const obj = require('obj');
const stub = sinon.stub(obj, 'method').emits('some event', arg1, arg2);
const spy = sinon.spy();

obj.on('some event', spy);
obj.method();
expect(spy.calledOnce).to.equal(true);
expect(spy.firstCall.args).to.deep.equal([arg1, arg2]);

Does this seem feasible? I could try to make an implementation of this, just not sure how feasible it is realistically.

@mantoni
Copy link
Member

mantoni commented May 14, 2016

You can use any event emitter for that. Either stub on or even better, simply call emit on the emitter in your test code.

@mantoni
Copy link
Member

mantoni commented May 14, 2016

Here are two ways how you can do it in your particular example:

const stub = sinon.stub(obj, 'method', function () {
  obj.emit('some event');
});

Alternatively:

const stub = sinon.stub(obj, 'method');
// ...

obj.method();
obj.emit('some event');

It would be out of scope for Sinon to add library or environment specific logic for something like event emitters.

If you have more questions about best practices on how to use Sinon with event emitters, please post questions on the Sinon.JS mailinglist, so the bigger community can help answer your questions.

@mantoni mantoni closed this as completed May 14, 2016
@perrin4869
Copy link
Contributor Author

Got it, thanks!!

@aleung
Copy link

aleung commented Feb 20, 2019

Another approach, if you have to use sinon.createStubInstance for some reason: make use of npm module extend:

import * as extend from 'extend';
import * as events from 'events';

const stub = sinon.createStubInstance(MyClass);
extend(stub, events.EventEmitter.prototype);

stub.on('event', () => { /* do something */ });
stub.method();
stub.emit('event');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants