Upgrading from V5 to V6
This is a long overdue refactor of the entire library. As feature requests have come in, the code and test suite had become increasingly spaghettified, and this new version is a massive improvement on the previous implementation.
For the most common use cases, and the basic mocking and inspecting api, very little has changed. The main changes are around how fetch-mock is configured and installed, and turning a few nice new features on by default (couldn’t do so in v5 as would’ve been a breaking change)
Changes
Configuration and installation
- Requires
async / await- for older node versions use v5, or require the transpiled version:require('fetch-mock/es5/server') - No change to mocking fetch as a global
- Uses whatever version of
node-fetchyou have already installed in your project i.e. can be used withnode-fetch2 .sandbox()no longer accepts a customPromiseimplementation as a parameter- Sandboxes can now be ‘sub-classed’ i.e. define some mocks on a sandbox, then call
.sandbox()on it to create a new one inheriting all its settings - No longer has a
setImplementations()method. Instead, assign customPromiseandfetchhelper classes directly to theconfigproperty of the fetch-mock instance. This may be done before or after sandboxing - No longer has a
configure()method. Instead set options directly on the.configproperty. See the api docs for a complete list of options
Routing
^is no longer a valid way of matching the beginning of strings; usebegin:insteadoverwriteRoutesoption allows for existing routes in a mock to be overwritten. It’s also possible to define multiple routes with ‘the same’ matcher. Default behaviour is to error. Set tofalseto use old “buffer-like” behavior
Responses
Content-Lengthheader generated by default for all responses (can be configured to not do so globally or per response.)- Objects will be converted to
JSONresponses if they contain any properties not listed in the docs as special response config options (previous behaviour was to convert if any of the properties were present). This means that e.g.{user: 'me', status: 'happy'}can easily be sent asJSON __redirectUrloption is now namedredirectUrltimesoption is now namedrepeat
Inspecting
- All inspection methods now filter, in addition to the existing check against
matcher.toString(), based on the following rules- An exact url
truefor matched calls onlyfalsefor unmatched calls onlyundefined(or no argument) includes all calls tofetchin order in a single array, i.e. no longer an object withmatchedandunmatchedproperties
- When
fetchwas last called with aRequestobject,lastUrl()andlastOpts()give easier access to theurland fullRequestobject