jest 不理解流类型和对象解构?

jest doesn't understand flow types and object destructuring?

我一直收到有关流类型和笑话的错误:

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 配置:

{
    "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 配置:

{
  "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,然后在方法内进行解构,它似乎工作得很好。考虑到这一点,这是允许同时使用 jestflow 类型的唯一方法吗?我更希望能够在签名中而不是在方法体内进行解构。

查看您的错误,您可能只是没有将第二个参数传递给函数。如果您调用 builder('foo'),您将尝试从 undefined.

中解构 returnType

使用第二个参数调用它:builder('foo', {}),或为参数提供默认值:

export default function builder(path: string, {returnType = 'object'}: BuilderOptionsType = {}): BuilderReturnType { ... }