chaijs / chai-spies

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

Async inner function not working with spy #120

Closed chr0m1ng closed 3 days ago

chr0m1ng commented 4 days ago

I have the following setup:

// file: foo.ts
export function innerFunc() {
   console.log('innerFunc')
   return Promise.resolve()
}

export async function outerFunc() {
   await innerFunc()
}
// file: foo.spec.ts
import * as Foo from './foo'
import chai from 'chai'
import spies from 'chai-spies'
chai.use(spies)

describe('test', () => {
  it('test', async () => {
    const mock = chai.spy.on(Foo, 'innerFunc')
    await Foo.outerFunc()
    chai.expect(mock).to.have.been.called.once
  })
})

But chai.expect(mock).to.have.been.called.once is throwing:

AssertionError: expected { Spy 'object.innerFunc' }
function innerFunc() {
    console.log('innerFunc');
    return Promise.resolve();
} to have been called once but got 0

When I debug the foo.ts file I can see that innerFunc doesn't have the __spy property, so it's not being mocked. Am I doing something wrong here or the library just don't cover this scenario?

Versions: "chai": "^4.2.0", "chai-spies": "^1.1.0" "mocha": "^7.1.1"

43081j commented 3 days ago

Presumably your project uses es modules. If that's the case, you can't mock/stub exports since, iirc, the object (Foo in this case) is unique per module/file

i.e you will be mutating the Foo object but that is only local to the foo.spec.ts. It won't affect the functions inside foo.ts

chr0m1ng commented 3 days ago

@43081j well I guess that's it then. Thanks!