我使用fetch-mock来模拟一些对服务器的请求。所有请求都是在这里发出的:
import fetchMock from 'fetch-mock'
import initialState from 'src/initial-state'
if (process.env.NODE_ENV === 'development') {
fetchMock.post('/some/endpoint', initialState.entities.multichannelEngagement)
}但是,不仅这个端点被模拟,而且所有使用同构-抓取进行的请求都被模拟
import 'isomorphic-fetch'
export function makeRequest(endpoint, config = {}) {
return window.fetch(endpoint, config)
.then(response => {
return response.json()
.then(json => ({ json, response }))
.catch(() => ({ response }))
})
.then(({ json, response }) => {
if (!response.ok) {
throw json ? json : new Error(response.statusText)
} else {
return json
}
})
.catch((e) => {
return Promise.reject(e)
})}
我的webpack.config.js如下:
import path from 'path'
import dotenv from 'dotenv'
import webpack from 'webpack'
import info from './package.json'
const resolvePath = p => path.join(__dirname, p)
const __DEV__ = process.env.NODE_ENV !== 'production'
const { parsed: env } = dotenv.load()
env.NODE_ENV = process.env.NODE_ENV
Object.keys(env).forEach(k => env[k] = JSON.stringify(env[k]))
const config = {
name: info.name,
entry: {
app: 'src/index',
vendor: Object.keys(info.dependencies)
},
output: {
path: __DEV__ ? resolvePath('public') : resolvePath('../analytics-server/server/public'),
filename: '/js/[name].js',
publicPath: '/',
debug: __DEV__,
pathinfo: __DEV__
},
module: {
preLoaders: [{
// NOTE: Run linter before transpiling
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modules/
}],
loaders: [{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/
}, {
// TODO: Remove after upgrading to webpack 2
test: /\.json$/,
loader: 'json'
}]
},
resolve: {
alias: {
src: resolvePath('src'),
core: resolvePath('src/core'),
components: resolvePath('src/components'),
modules: resolvePath('src/modules'),
services: resolvePath('src/services'),
resources: resolvePath('src/resources'),
locales: resolvePath('src/locales')
},
// NOTE: Empty string to properly resolve when providing extension
// TODO: Remove after upgrading to webpack 2
extensions: ['', '.js']
},
plugins: [
// NOTE: `NoErrorsPlugin` causes eslint warnings to stop the build process
// new webpack.NoErrorsPlugin(),
new webpack.optimize.CommonsChunkPlugin('commons', '/js/commons.js'),
new webpack.DefinePlugin({ process: { env } })
// new webpack.NormalModuleReplacementPlugin( /^fetch-mock$/, path.resolve( __dirname, 'node_modules', 'fetch-mock/src/client.js' ) )
],
eslint: {
configFile: resolvePath('.eslintrc')
}
}
if (__DEV__) {
config.devtool = 'source-map'
config.devServer = {
contentBase: 'public',
// NOTE: Options `inline` and `hot` shall be passed as CLI arguments
// inline: true,
// hot: true,
historyApiFallback: true
}
} else {
config.plugins.push(...[
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: true,
acorn: true
})
])
}
export default config当我运行这个应用程序时,我得到的错误是“fetch-mock.js:93UNAUCTURE Error: No fallback response defined for get to http://localhost:3000/api/session”,这是在应用程序中发出的第一个请求。
不知道为什么fetch-mock要模仿所有的请求。在chrome控制台上进行计算时,makeRequest函数上的fetch的值是fetch-mock函数,但据我所知这是正确的。
顺便说一句,我不是在测试环境,我在开发,因为我需要我的后端被嘲笑,因为它还没有完成。
你知道为什么会发生这种事吗?
提前感谢
发布于 2017-01-26 22:22:17
这个问题是因为fetch-mock的主要目标是帮助测试。在测试环境中,如果你在调度任何非模拟调用时得到一个异常,情况会更好。
但是,您可以添加一个委托给原始fetch的catch处理程序,以便将任何未模拟的请求传递给真正的fetch。类似于以下内容:
/* FAKE FETCH ME */
fetchMock.get('/session', function getSession(url, opts) {
const jwt = extractToken(opts)
if (!jwt || jwt !== fakeToken) {
return delay({
status: 401,
body: JSON.stringify({
details: 'Unauthorized'
})
})
}
return delay({
status: 200,
body: JSON.stringify({
success: true,
data: fakeUserDetails
})
})
})
.catch(unmatchedUrl => {
// fallover call original fetch, because fetch-mock treats
// any unmatched call as an error - its target is testing
return realFetch(unmatchedUrl)
})这个库曾经有一个选项,但在V5中被删除了。请参阅此处的文档:
以前版本的fetch-mock中的
有一个greed属性,设置为
进行响应
这现在已经被一个.catch()方法所取代,该方法接受与对.mock(匹配器,响应)的正常调用相同类型的响应。它还可以采用任意函数来完全定制不匹配调用的行为。它是可链接的,可以在其他.mock()调用之前或之后调用。用于检查不匹配调用的api保持不变。
发布于 2020-08-20 16:47:13
从fetch-mock v.6.5开始,有了一个名为fallbackToNetwork的新配置属性,它允许您控制fetch-mock如何处理未处理(不匹配)的调用
http://www.wheresrhys.co.uk/fetch-mock/#usageconfiguration
https://stackoverflow.com/questions/41868698
复制相似问题