-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
8 changed files
with
94 additions
and
5,317 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,29 +1,39 @@ | ||
import mockXhr from './src/xhr'; | ||
import mockFetch from './src/fetch'; | ||
export default class ChaosRequest { | ||
constructor(shouldChangeResponse, getResponse) { | ||
|
||
const shouldChangeResponseFunction = function(url) { | ||
const random = Math.random(); | ||
console.log(random); | ||
if (random <= 0.2) { | ||
console.log('true'); | ||
return true; | ||
this.shouldChangeResponse = typeof shouldChangeResponse === 'function' ? shouldChangeResponse : function() { | ||
return true; | ||
}; | ||
|
||
this.getResponse = typeof getResponse === 'function' ? getResponse : function() { | ||
return { | ||
body: JSON.stringify({}), | ||
init: { | ||
status: 200, | ||
statusText: 'OK', | ||
headers: { | ||
'Content-type': 'application/json', | ||
}, | ||
}, | ||
}; | ||
}; | ||
} | ||
return false; | ||
} | ||
|
||
const getResponseFunction = function(url) { | ||
return { | ||
responseText: '{}', | ||
status: 400, | ||
statusText: 'Bad Request', | ||
}; | ||
} | ||
mock() { | ||
this.fetch = window.fetch; | ||
window.fetch = (...args) => { | ||
if (this.shouldChangeResponse(args)) { | ||
return new Promise((resolve) => { | ||
const response = this.getResponse(args); | ||
|
||
resolve(new Response(response.body, response.init)); | ||
}); | ||
} | ||
return this.fetch.apply(null, args); | ||
} | ||
} | ||
|
||
export default { | ||
mock: function(shouldChangeResponse, getResponse) { | ||
shouldChangeResponse = typeof shouldChangeResponse === 'function' ? shouldChangeResponse : shouldChangeResponseFunction; | ||
getResponse = typeof getResponse === 'function' ? getResponse : getResponseFunction; | ||
mockXhr(shouldChangeResponse, getResponse); | ||
mockFetch(window, shouldChangeResponse, getResponse); | ||
restore() { | ||
window.fetch = this.fetch; | ||
} | ||
}; | ||
}; |
Oops, something went wrong.