* Initializes the mock by temporary overwriting `global.fetch`.
()
| 30 | * Initializes the mock by temporary overwriting `global.fetch`. |
| 31 | */ |
| 32 | init() { |
| 33 | this.originalFetch = global?.fetch; |
| 34 | |
| 35 | global.fetch = ( |
| 36 | url: RequestInfo | URL, |
| 37 | config: RequestInit | { [key: string]: any } | undefined, |
| 38 | ) => { |
| 39 | for (let mock of this.mocks) { |
| 40 | // match url and method |
| 41 | if (mock.url !== url || config?.method !== mock.method) { |
| 42 | continue; |
| 43 | } |
| 44 | |
| 45 | // match body params |
| 46 | if (mock.body) { |
| 47 | let configBody: { [key: string]: any } = {}; |
| 48 | |
| 49 | // deserialize |
| 50 | if (typeof config?.body === "string") { |
| 51 | configBody = JSON.parse(config?.body) as { [key: string]: any }; |
| 52 | } |
| 53 | |
| 54 | let hasMissingBodyParam = false; |
| 55 | for (const key in mock.body) { |
| 56 | if ( |
| 57 | typeof configBody[key] === "undefined" || |
| 58 | JSON.stringify(configBody[key]) != |
| 59 | JSON.stringify(mock.body[key]) |
| 60 | ) { |
| 61 | hasMissingBodyParam = true; |
| 62 | break; |
| 63 | } |
| 64 | } |
| 65 | if (hasMissingBodyParam) { |
| 66 | continue; |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | if (mock.additionalMatcher && !mock.additionalMatcher(url, config)) { |
| 71 | continue; |
| 72 | } |
| 73 | |
| 74 | const response = { |
| 75 | url: url, |
| 76 | status: mock.replyCode, |
| 77 | statusText: "test", |
| 78 | json: async () => { |
| 79 | if (typeof mock.replyBody == "function") { |
| 80 | return mock.replyBody(); |
| 81 | } |
| 82 | |
| 83 | return mock.replyBody || {}; |
| 84 | }, |
| 85 | } as Response; |
| 86 | |
| 87 | return new Promise((resolve, reject) => { |
| 88 | setTimeout(() => { |
| 89 | if (!!config?.signal?.aborted) { |
no outgoing calls
no test coverage detected