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

Cannot attach spy on the same function more than once #90

Closed
drochgenius opened this issue Dec 20, 2017 · 2 comments
Closed

Cannot attach spy on the same function more than once #90

drochgenius opened this issue Dec 20, 2017 · 2 comments

Comments

@drochgenius
Copy link

drochgenius commented Dec 20, 2017

I have a suite of tests using chai spies. Basically, every test case attaches a new spy and records the number of times that spy gets called, and with which arguments.
All is fine, until I switch from 0.7.1 to the master branch where I get the following error:

Error: "foo" is already a spy

Here is a simple script that replicates the issue:

const chai = require('chai');
const spies = require('chai-spies');
const { EventEmitter } = require('events');
chai.use(spies);

const emitter = new EventEmitter();

function foo() {
    const spy = chai.spy.on(emitter, 'emit');
};

function bar() {
    const spy = chai.spy.on(emitter, 'emit');
}

foo(); // OK
bar(); // Error: "emit" is already a spy

The above script works fine on version 0.7.1, but throws the error on the master branch. This looks to me like a regression.

I have used Node EventEmitter here, but you can reproduce with any other function.

Regards

@stalniy
Copy link
Contributor

stalniy commented Dec 23, 2017

@drochgenius this is expected behavior. This is because you are trying to spy the same method of the same "global" object.

Before spying second time, now you need to call chai.spy.restore()

const chai = require('chai');
const spies = require('chai-spies');
const { EventEmitter } = require('events');
chai.use(spies);

const emitter = new EventEmitter();

function foo() {
    const spy = chai.spy.on(emitter, 'emit');
};

function bar() {
    const spy = chai.spy.on(emitter, 'emit');
}

foo(); // OK
chai.spy.restore() // <-----
bar(); // Error: "emit" is already a spy

@drochgenius
Copy link
Author

Awesome, that works for me!

Thanks @stalniy

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

2 participants