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

support mock injections usable to mock globalThis value #205

Merged
merged 14 commits into from
May 31, 2023

Conversation

iambumblehead
Copy link
Owner

@iambumblehead iambumblehead commented May 29, 2023

closes #198

@koshic @Swivelgames and/or @tommy-mitchell please review.

Changes here allow esmock to be called this way. esmock adds an 'import' statement at the top of the file, importing the mock-versions of the definitions,

const mockedReq = await esmock('../src/req.js', {
  import: {
    fetch: () => '[{"name":"jim","id":1},{"name":"jen","id":2}]'
  }
})

await mockedReq()
// '[{"name":"jim","id":1},{"name":"jen","id":2}]'

req.js

import { fetch } from 'file:///esmockDummy.js' // this line added by esmock

export default async url => fetch(url + '?limit=10')

@iambumblehead
Copy link
Owner Author

very want to merge this

@koshic
Copy link
Collaborator

koshic commented May 31, 2023

@iambumblehead look ok for first time implementation, thx!

But there are obvious pitfalls with code directly uses globalThis, because 'globalThis.fetch === fetch' returns false after injection. So we have to patch globalThis object.

@iambumblehead
Copy link
Owner Author

Maybe it will become necessary to mock "globalThis" specifically and maybe not. This PR allows one to write unit-tests around fetch and other globals. It also enables importing mock values in creative ways, to alter the way a script might use "globalThis".

@iambumblehead
Copy link
Owner Author

thanks for the approval will merge and publish sometime over the next day or so

@iambumblehead iambumblehead merged commit 1737bf2 into master May 31, 2023
@iambumblehead iambumblehead deleted the start-global-mock branch May 31, 2023 06:46
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

Successfully merging this pull request may close these issues.

Overriding globalThis per mock
3 participants