Proposal: Change vi.mock
signature to return the mocked module instead of void
#3777
webbertakken
started this conversation in
Ideas
Replies: 1 comment 9 replies
-
Why can't you just import the module with |
Beta Was this translation helpful? Give feedback.
9 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Introduction
Vocabulary
unit
: a single method or functionside-effect
: another function that is called from inside your unitunit test
: testing a unit without testing the logic of side-effectsUse case
Consider making a dead simple unit test that needs to mock either a 3rd part or local module that's called as a side-effect.
vi.mock('./localModule')
orvi.mock('third-party-module')
at the top of the file as per the docs [1, 2].Now try to imagine also asserting that methods from that module are only called once by your unit.
Explanation
You won't get this to work before realising a few things:
vi.mock()
returnsvoid
, meaning it doesn't give you a reference to any of the methods, that you can assert on.vi.mock()
, you'll soon find out that you can't do that because the act of mocking a module is hoisted (pulled to the top at runtime). See "Invalid example" below.Invalid example
Correct example
Better correct example
Proposal 1 (superseded)
I'd propose forvi.mock
to return the mocked module (the outcome of the factory method) and make it accessible much like thejsCookie
variable is in "Correct example".This would effectively combine the syntax ofvi.hoisted
andvi.mock
into a single call for many use cases and make those tests easier to remember how to write, as well as lot more readable.This would look even simpler with named exports/imports, as you don't needdefault
.For complex methods the pattern might be repeated several times.
Proposal 2 (current)
Other thoughts
Perhaps there are better signatures that are repeatable for both
./localModule
andthird-party-module
than I've found so far ("Correct example"), in which case please share them 🧡Beta Was this translation helpful? Give feedback.
All reactions