chaijs / chai-spies

Spies for Chai Assertion Library.
MIT License
132 stars 29 forks source link

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

Closed drochgenius closed 6 years ago

drochgenius commented 6 years ago

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 commented 6 years ago

@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 commented 6 years ago

Awesome, that works for me!

Thanks @stalniy