问题描述
假设我想在特定 URL 上模拟网络中的错误,我是这样开始的:
let intercepts = {}
let hasStubbedRequests = false
class Intercept {
url: string | RegExp
method?: string
error: string
constructor({ url,method,error }) {
this.url = url
this.method = method
this.error = error
}
match({ url,method }) {
const matchesUrl = this.url instanceof RegExp ?
this.url.test(url) :
this.url === url
const matchesMethod = this.method ?
this.method === method :
true
return matchesUrl && matchesMethod
}
}
const getXHRIntercept = (xhr) => {
for (const key in intercepts) {
let intercept = intercepts[key]
const request = {
url: xhr.
}
if (intercept.match(request)) {
intercept.queue()
return true
}
}
return false
}
const getFetchIntercept = (options = {}) => {
}
const stubRequests = () => {
if (hasStubbedRequests) {
return
}
const originalOpen = XMLHttpRequest.prototype.open
XMLHttpRequest.prototype.open = function(method,url) {
this.__method__ = method
this.__url__ = url
return originalOpen.apply(this,arguments)
}
const originalSend = XMLHttpRequest.prototype.send
XMLHttpRequest.prototype.send = function(){
const intercept = getXHRIntercept(this)
if (intercept) {
const respondWithError = () => {
}
setTimeout(respondWithError,100)
} else {
return originalSend.apply(this,arguments)
}
}
const originalFetch = window.fetch
window.fetch = function(url,options = {}){
if (getFetchIntercept({ ...options,url })) {
return new Promise(() => {
})
} else {
return originalFetch.apply(this,arguments)
}
}
}
我现在面临的问题是,如何向 XMLHttpRequest 返回错误?所以我基本上对请求进行存根,但为 XMLHttpRequest 调用正确的错误处理程序。
我想这样做,以便错误返回。错误应该调用正确的错误处理程序,但是否有不止一种方法可以做到这一点?例如 xhr.onerror
与 xhr.triggerEvent(...)
?我不知道如何正确地做到这一点。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)