1 | const { debug } = require('./debug');
|
2 | const setUpAndTearDown = require('./set-up-and-tear-down');
|
3 | const fetchHandler = require('./fetch-handler');
|
4 | const inspecting = require('./inspecting');
|
5 | const matchers = require('./matchers');
|
6 | const compileRoute = require('./compile-route');
|
7 |
|
8 | const FetchMock = Object.assign(
|
9 | {},
|
10 | fetchHandler,
|
11 | setUpAndTearDown,
|
12 | inspecting,
|
13 | compileRoute,
|
14 | matchers
|
15 | );
|
16 |
|
17 | FetchMock.config = {
|
18 | fallbackToNetwork: false,
|
19 | includeContentLength: true,
|
20 | sendAsJson: true,
|
21 | warnOnFallback: true,
|
22 | overwriteRoutes: undefined,
|
23 | };
|
24 |
|
25 | FetchMock.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 |
|
41 | FetchMock.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 |
|
48 | FetchMock.sandbox = function () {
|
49 | debug('Creating sandboxed fetch-mock instance');
|
50 |
|
51 |
|
52 |
|
53 | const fetchMockProxy = (url, options) => sandbox.fetchHandler(url, options);
|
54 |
|
55 | const sandbox = Object.assign(
|
56 | fetchMockProxy,
|
57 | FetchMock,
|
58 | this.createInstance(),
|
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 |
|
72 | FetchMock.getOption = function (name, route = {}) {
|
73 | return name in route ? route[name] : this.config[name];
|
74 | };
|
75 |
|
76 | module.exports = FetchMock;
|