UNPKG

2.3 kBJavaScriptView Raw
1const { debug } = require('./debug');
2const setUpAndTearDown = require('./set-up-and-tear-down');
3const fetchHandler = require('./fetch-handler');
4const inspecting = require('./inspecting');
5const matchers = require('./matchers');
6const compileRoute = require('./compile-route');
7
8const FetchMock = Object.assign(
9 {},
10 fetchHandler,
11 setUpAndTearDown,
12 inspecting,
13 compileRoute,
14 matchers
15);
16
17FetchMock.config = {
18 fallbackToNetwork: false,
19 includeContentLength: true,
20 sendAsJson: true,
21 warnOnFallback: true,
22 overwriteRoutes: undefined,
23};
24
25FetchMock.createInstance = function () {
26 debug('Creating fetch-mock instance');
27 const instance = Object.create(FetchMock);
28 instance._uncompiledRoutes = (this._uncompiledRoutes || []).slice();
29 instance._matchers = this._matchers.slice();
30 instance.routes = instance._uncompiledRoutes.map((config) =>
31 instance.compileRoute(config)
32 );
33 instance.fallbackResponse = this.fallbackResponse || undefined;
34 instance.config = Object.assign({}, this.config || FetchMock.config);
35 instance._calls = [];
36 instance._holdingPromises = [];
37 instance.bindMethods();
38 return instance;
39};
40
41FetchMock.bindMethods = function () {
42 this.fetchHandler = FetchMock.fetchHandler.bind(this);
43 this.reset = this.restore = FetchMock.reset.bind(this);
44 this.resetHistory = FetchMock.resetHistory.bind(this);
45 this.resetBehavior = FetchMock.resetBehavior.bind(this);
46};
47
48FetchMock.sandbox = function () {
49 debug('Creating sandboxed fetch-mock instance');
50 // this construct allows us to create a fetch-mock instance which is also
51 // a callable function, while circumventing circularity when defining the
52 // object that this function should be bound to
53 const fetchMockProxy = (url, options) => sandbox.fetchHandler(url, options);
54
55 const sandbox = Object.assign(
56 fetchMockProxy, // Ensures that the entire returned object is a callable function
57 FetchMock, // prototype methods
58 this.createInstance(), // instance data
59 {
60 Headers: this.config.Headers,
61 Request: this.config.Request,
62 Response: this.config.Response,
63 }
64 );
65
66 sandbox.bindMethods();
67 sandbox.isSandbox = true;
68 sandbox.default = sandbox;
69 return sandbox;
70};
71
72FetchMock.getOption = function (name, route = {}) {
73 return name in route ? route[name] : this.config[name];
74};
75
76module.exports = FetchMock;