【发布时间】:2016-04-07 02:14:46
【问题描述】:
我有以下设置。我现在正在尝试模拟我的后端。
我有一个异步 redux 操作如下:
import * as types from './../constants/actionTypes.jsx'
import fetch from 'isomorphic-fetch'
var fetchMock = require('fetch-mock');
export function fetchEntry(entry){
return dispatch => {
dispatch(requestEntry(entry));
fetchMock
.mock(`http://localhost:8080/entry/${entry}`, {content: 'blah blah'});
return fetch(`http://localhost:8080/entry/${entry}`)
.then(response => response.json())
.then(json => dispatch(receiveEntry(entry, json)))
.catch(err => console.log(err))
}
}
这就是我的 webpack 配置设置部分的方式:
entry: {
app: path.resolve(__dirname, 'app/routes.jsx'),
vendor: [
'react',
'react-dom',
'history',
'react-router',
'redux',
'react-redux',
'redux-simple-router',
'react-css-modules',
'alloyeditor',
'redux-form',
'react-toggle',
'react-select',
'isomorphic-fetch',
'redux-thunk',
'fetch-mock'
]
},
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: /node_modules/,
query: {
presets: ['react', 'es2015']
}
},
我正在使用babel-pollyfill 作为 Promise pollyfill。这在import 'babel-polyfill' 上方的入口文件(route.jsx) 中是必需的,因此包含在bundle.js 文件的顶部。 fetch 在浏览器控制台中也可以作为全局变量使用。
我使用webpack-dev-server --content-base build/ --inline --hot --progress --colors 作为开发服务器。
在浏览器控制台中,我在 URL 上收到 404,似乎路由请求没有被拦截? GET http://localhost:8080/entry/1 404 (Not Found)。另外从 catch 中抛出的错误如下SyntaxError: Unexpected token C.
谢谢
编辑:
我只是尝试使用 nock 也没有运气。我也从使用 bable-polyfill 切换到 es6-promise 无济于事。我已经没有想法为什么这个 fetch-mock 没有拦截请求。我在控制台上记录了fetchMock 并定义了路线。
_calls: Object
__proto__: Object
_matchedCalls: Array[0]
length: 0
__proto__: Array[0]
_unmatchedCalls: Array[0]
isMocking: true
mockedContext: Window
realFetch: ()
routes: Array[2]
0: Object
__unnamed: true
matcher: (url, options)
name: "http://localhost:8080/entry/1"
response: Object
content: "blah blah"
__proto__: Object
__proto__: Object
1: Object
__unnamed: true
matcher: (url, options)
name: "http://localhost:8080/entry/1"
response: Object
content: "blah blah"
__proto__: Object
__proto__: Object
length: 2
__proto__: Array[0]
__proto__: FetchMock
在 chrome 控制台中运行 fetch 也会产生以下函数。
function mock(url, opts) {
var response = _this.router(url, opts);
if (response) {
debug('response found for ' + url);
return mockResponse(url, response);
} else {
deb…
【问题讨论】:
-
你让它工作了吗?
标签: javascript reactjs ecmascript-6 webpack babeljs