kan*_*aki 1 mocking fetch reactjs webpack fetch-mock
我正在使用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)
}
Run Code Online (Sandbox Code Playgroud)
但是,不仅此端点是模拟的,而且所有同构提取的请求
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)
})
Run Code Online (Sandbox Code Playgroud)
}
我的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
Run Code Online (Sandbox Code Playgroud)
运行应用程序时遇到的错误是“ fetch-mock.js:93未捕获的错误:没有为GET定义到http:// localhost:3000 / api / session的回退响应”,这是应用程序中的第一个请求。
不知道为什么fetch-mock模拟所有请求。在chrome控制台上进行评估时,makeRequest函数上的访存值是fetch-mock函数,但据我所知这是正确的。
顺便说一句,我不在测试环境中,我在开发中,因为我需要模拟我的后端,因为它尚未完成。
知道为什么会这样吗?
提前致谢
引起该问题是因为fetch-mock的主要目标是帮助测试。在测试环境中,最好让调度的所有非模拟呼叫都获得异常。
但是,您可以添加一个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)
})
Run Code Online (Sandbox Code Playgroud)
该库曾经有一个选项,但是在V5中已将其删除。请参阅此处的文档:
在以前的版本中,fetch-mock具有greed属性,设置为
- 好-无与伦比的通话回复200
- 差-无与伦比的通话错误
- 无-允许不匹配的呼叫使用本机提取和网络
现在,该方法已由.catch()方法代替,该方法接受与正常调用.mock(matcher,response)相同类型的响应。它还可以使用任意函数来完全自定义不匹配调用的行为。它是可链接的,可以在其他对.mock()的调用之前或之后调用。用于检查不匹配调用的api保持不变。
| 归档时间: |
|
| 查看次数: |
14810 次 |
| 最近记录: |