dce-stub
A simple way to stub default-only dependencies. This project currently only works for stubbing the default export of a module.
We utilize dependency injection, so stubbed modules cannot be used until time of test (not at import time). For more info, see step 4 in the instructions below.
Usage
dce-stub
1. Import ;
2. Import the dependencies you wish to stub using * syntax
In your spec:
;...
In the module you are testing:
; ... // When using the dependency, use the .default property:myDependencydefault......
runStubbed
function
3. Run your tests within the Call runStubbed
with two arguments:
- replacements
object|object[]
– either one or many stub replacements, each of the form{ dep, stub }
wheredep
is the dependency andstub
is the stubbed version of the dependency - test
function
– tests to run while the dependency is stubbed (dependencies are restored once the function finishes). Function may be asynchronous or synchronous
;
If you have more than one dependency to stub, just use a list:
...// Define stub replacementsconst replacements = dep: myDependency stub: <stub of myDependency> dep: secondDepencency stub: <stub of secondDependency> ...; // Run theawait ;
4. Configure/use dependencies at time of use
We use dependency injection, which means that the stubbed version of the dependency is not injected at import time. Instead, it is injected when the test runs.
Don't configure/initialize/use stubbed libraries until time of test:
Example: we are using a library lms
that must be initialized before being used.
Wrong way:
;const api = lmsdefault;{thisid = id;}{return apicourse;}...
Right way:
;{thisid = id;thisapi = lms;}{return thisapicourse;}...
Another right way:
(if there is no cost to re-initializing over and over)
;{thisid = id;}{const api = lms;return thisapicourse;}...
Note: One concrete example of such a library that can be re-initialized with no cost, is caccl/client/cached
Example
We have two helpers:
getNameFromServer
– pulls the current user's first name from the servergenIntro
– a script that callsgetNameFromServer
and generates a welcome message
Our goal is to write a unit test for genIntro
, isolating it from getNameFromServer
. Thus, we want to import genIntro
while replacing getNameFromServer
with a fake stubbed version of that module.
getNameFromServer.js
{ return ;};
genIntro.js
; { // Get the current user's name const name = await ; // Create the message return `Hi ! It is a pleasure to meet you.`;};
genIntro.spec.js
; // Import module to test; // Import dependencies we want to stub; // Create the getNameFromServer stubconst getNameFromServerStub = { return 'Divardo';}; // Tests;