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

v7 breaks sinon stubbing #410

Closed
hldswrth opened this issue Apr 11, 2024 · 4 comments
Closed

v7 breaks sinon stubbing #410

hldswrth opened this issue Apr 11, 2024 · 4 comments

Comments

@hldswrth
Copy link

We use sinon in our (common JS) unit tests for code which uses the tar.x function. This work fine with v6.

const tar = require('tar')
const sinon = require('sinon')
const tarXStub = sinon.stub(tar, 'x')
.. run test for code which calls the x function...
tarXstub.restore()

When using v7 with no other changes to our code or tests, the tests which involve the x function fail with error TAR_BAD_ARCHIVE: Unrecognized archive format which indicates the stubbing is not effective, despite the sinon.stub and sinon.restore calls appearing to be successful.

@AviVahl
Copy link

AviVahl commented Apr 11, 2024

x is now a getter, because the codebase uses typescript and native esm, and live bindings need to work (even when transpiled to commonjs).

possible workarounds:

  • require('tar/extract') directly in your code and mock the extract method.
  • mock the fn on your end that calls tar.

@hldswrth
Copy link
Author

Thanks for the quick response. I did try changing my code to call tar.extract insted of tar.x but this cannot be stubbed by sinon, doing a sinon.stub(tar, 'extract') results in TypeError: Descriptor for property extract is non-configurable and non-writable.
If I require('tar/extract') I don't see how I would stub that with sinon.

@AviVahl
Copy link

AviVahl commented Apr 11, 2024

Rather than requiring tar in the implementation, require tar/extract and use the extract fn exported from that module.

Do the same where you mock. That module directly exports the fn extract, meaning it can be mocked, as it's not a getter.

@hldswrth
Copy link
Author

Thanks! The following does appear to at least pass unit tests again:

// code:
const extract = require('tar/extract')
return extract.extract(options)

// test:
const extract = require('tar/extract')
const extractStub = sinon.stub(extract, 'extract')

@isaacs isaacs closed this as completed Jun 19, 2024
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