0
votes

I have multiple Mocha test files using one shared base file known as testBase.js. It's responsible for setting up all stubs and spies.

If I run individual file through mocha all test cases pass but when it run tests through mocha *.js, test cases begin to fail and raise error

TypeError: Attempted to wrap send which is already wrapped

Here are my beforeEach and afterEach blocks

beforeEach(function (done) {
    context.alexaSpy = sinon.spy(alexa, "send");
}

beforeEach(function (done) {
    context.alexaSpy.restore();
}

I actually printed out logs in both blocks and there is a strange thing I noticed. I see logs this way

-- BeforeEach Fired Test1
-- BeforeEach Fired Test1
-- AfterEach Fired Test1
-- AfterEach Fired Test1

I don't know why it's calling twice and its the root cause of the issue. BefireEach must not call twice for one mocha test.

Does importing multiple files call beforeEach twice? Can someone suggest any possible solution to this? I tried sinon.sandbox too but it does not work

1
Are beforeEach and afterEach located in the root of testBase file? Or they are wrapped in a function and exported somehow? Please provide more information. - vsenko
Both functions are in base file and they are in testInit function which is then exported to the test cases - Hassnain Alvi
You need to export the pure functions - not wrapped in beforeEach and afterEach. Then pass them into beforeEach and afterEach in the describe blocks in each file. Otherwise you will have your errors as they all apply to the outer (global) scope. I describe this at the bottom of my answer - oligofren

1 Answers

0
votes

We need to see how you require in the base file to be certain.

My guess is simply that you require the file from multiple files, and each time you do this you add the setup and teardown functions. That happens because all the tests share the same outer scope. Requiring the Base file ten times will add the beforeEach ten times too.

The right way to do this would be using sinon.sandbox or sinon-test. Much easier to avoid one test interfering with the next.

But no matter what you do, you would need to export the function and run that in a beforeEach in each file

Typically like this

const base = require('./base')

describe('module one', ()=> {
    beforeEach(base.commonStubs);

    it('should.... ',..);
 })