我继续使用流类型和jest获取此错误:
TypeError: Cannot read property 'returnType' of undefined
at builder (src/index.js:22:195)
at Object.<anonymous> (__test__/index.spec.js:6:53)
at process._tickCallback (internal/process/next_tick.js:103:7)
以下是我的整个设置:
应用程序代码:
// @flow
type BuilderReturnType = {
path: string,
query: string
}
type BuilderOptionsType = {
returnType?: string
}
export default function builder(path: string, {returnType = 'object'}: BuilderOptionsType): BuilderReturnType {
const query = {};
let queryResult = null;
if (returnType === 'string') {
queryResult = doSomething(query);
}
return {
path,
query: queryResult !== null ? queryResult : query
}
}
.babelrc
config:
{
"presets": [
"es2015", "jest"
],
"plugins": [
"transform-object-rest-spread",
"transform-flow-strip-types"
],
"env": {
"test": {
"presets": [
"es2015", "jest"
],
"plugins": [
"transform-object-rest-spread",
"transform-flow-strip-types"
]
}
}
}
jest.json
config:
{
"bail": true,
"verbose": true,
"collectCoverage": true,
"coverageDirectory": "./coverage",
"coverageThreshold": {
"global": {
"branches": 100,
"functions": 100,
"lines": 100,
"statements": 100
}
},
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest"
}
}
似乎同时使用解构和流类型的方法签名存在问题(BuilderOptionsType
对象):
export default function builder(path: string, {returnType = 'object'}: BuilderOptionsType): BuilderReturnType { ... }
如果我将{returnType = 'object'}
更改为options
然后在方法中进行解构,则它似乎完全正常。考虑到这一点,这是允许同时使用jest
和flow
类型的唯一方法吗?我更喜欢能够在签名中而不是在方法体内进行解构。
答案 0 :(得分:0)
查看错误,您可能无法将第二个参数传递给函数。如果您致电builder('foo')
,您将尝试从returnType
解构undefined
。
使用第二个arg:builder('foo', {})
调用它,或者为参数提供默认值:
export default function builder(path: string, {returnType = 'object'}: BuilderOptionsType = {}): BuilderReturnType { ... }