我有一个使用Redux,Flow类型和Jest的React应用程序。为了创建我的减速器,我使用了自定义的通用工厂createReducer<S> (initialState: S, actions: any): Reducer<S>
为了创建一些减速器,我要做:
const FooReducer = createReducer<FooState>(initialState, {
'ACTION_ADD_USER': () => 'Foo',
})
我有以下测试案例:
// @flow
import { createReducer } from 'create-reducer'
type AppState = { name: string }
const initialState: AppState = { name: '' }
const NameReducer = createReducer<AppState>(initialState, {
'NAME_CHANGE': (state, name) => ({ ...state, name })
})
it('should change the name', () => {
const action = { type: 'NAME_CHANGE', name: 'bar' }
expect(NameReducer({ name: 'foo' }, action)).toEqual({ name: 'bar' })
})
玩笑抛出以下错误:
FAIL temp.spec.jsx ● Test suite failed to run ReferenceError: AppState is not defined 7 | const initialState: AppState = { name: '' } 8 | > 9 | const NameReducer = createReducer<AppState>(initialState, { | ^ 10 | 'NAME_CHANGE': (state, name) => ({ ...state, name }) 11 | }) 12 | at Object.AppState (temp.spec.jsx:9:35)
由于某种原因,Jest无法找到我的类型定义,即使它已在此处声明也是如此。我一直在寻找解决方法,但到目前为止还没有任何运气。希望有人知道这里出了什么问题?
附录:
环境
babel-core 6.26.0 babel-jest 23.6.0 babel-loader 6.4.1 babel-preset-flow 6.23.0 flow-bin 0.89.0 flow-typed 2.2.0 jest 23.6.0
.babelrc (已更新):
{
"plugins": [
"syntax-dynamic-import",
"transform-runtime",
"transform-object-rest-spread",
"transform-class-properties",
"transform-es2015-destructuring"
],
"presets": [
"babel-preset-flow",
"es2015",
"react",
"stage-0"
],
"env": {
"start": {
"presets": [
"react-hmre"
]
},
"test": {
"presets": [
"es2015",
"react",
"stage-0"
]
}
}
}
jest.config.js
module.exports = {
roots: ['<rootDir>/spec/javascripts'],
moduleNameMapper: {
'c3': '<rootDir>/__mocks__/c3.js',
'\\.(css|less|sass|scss)$': '<rootDir>/spec/javascripts/__mocks__/styleMock.js',
'\\.(gif|ttf|eot|svg)$': '<rootDir>/spec/javascripts/__mocks__/fileMock.js'
},
moduleFileExtensions: [
'jsx',
'js'
],
setupFiles: [
'<rootDir>/spec/javascripts/__mocks__/global-mocks.js'
],
moduleDirectories: [
'node_modules',
'app/javascript/src'
],
transform: {
'^.+\\.jsx?$': './node_modules/babel-jest'
},
testURL: 'http://localhost',
testRegex: '.*.spec.jsx',
verbose: true
}
createReducer.js
function createReducer<S> (initialState: S, handlers: any): Reducer<S> {
return function reducer (state = initialState, action) {
if (handlers.hasOwnProperty(action.type)) {
return handlers[action.type](state, action)
} else {
return state
}
}
}
答案 0 :(得分:0)
babel-preset-flow被作为flow
文件中预设的.babelrc
调用。这是更新的版本:
{
"plugins": [
"syntax-dynamic-import",
"transform-runtime",
"transform-object-rest-spread",
"transform-class-properties"
],
"presets": [
"flow",
"es2015",
"react",
"stage-0"
],
"env": {
"start": {
"presets": [
"react-hmre"
]
}
}
}
默认和测试环境需要相同的配置(此处不需要环境/测试配置)。
transform-es2015-destructuring
插件已经包含在babel-preset-es2015中。