【问题标题】:jest doesn't understand flow types and object destructuring?开玩笑不了解流类型和对象解构?
【发布时间】:2017-05-21 17:51:12
【问题描述】:

我不断收到有关流类型和玩笑的错误:

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 类型的唯一方法吗?我希望能够在签名中解构而不是在方法体中。

【问题讨论】:

    标签: javascript babeljs jestjs flowtype


    【解决方案1】:

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

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

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

    【讨论】:

    • 啊,我觉得{returnType = 'object'}: BuilderOptionsType够了
    猜你喜欢
    • 1970-01-01
    • 2017-07-11
    • 2022-01-22
    • 2019-06-24
    • 2018-06-22
    • 2021-11-30
    • 1970-01-01
    • 2017-12-19
    • 2017-09-11
    相关资源
    最近更新 更多