Reputation: 1607
How can I test functions of ECMAScript Modules (ESM) (or JavaScript Modules) that depend on the local state of their module? Specifically, I want to mock the local state within the module.
From this article http://exploringjs.com/es6/ch_modules.html, I understand that:
import
s are read-only views on export
sThus, while I could export a local variable, and import that local variable from the test and then modifiy it, because it’s read-only I’ll get an error.
Q) How can I mock the local state of an ES6 module? When it's type:
Example sumModule.js
- How can I mock this to set the sum, as I wish that is appropriate, for the test? Zero, may not be appropriate.
let sum = 0 // local state - type number example
export function addToSum (num) {
sum += num;
return sum
}
Upvotes: 1
Views: 316
Reputation: 1607
I solved this by adding a new function intended only for test use:
export function setMockNum (mock) {
num = mock
}
And I can do the same for functions and objects too.
It's readable (the intent is clear), and it allows me to move forward.
Upvotes: 1