【问题标题】:Jest TypeError: Cannot read property 'bind' of undefinedJest TypeError:无法读取未定义的属性“绑定”
【发布时间】:2021-11-07 08:07:41
【问题描述】:

我正在尝试在测试中执行以下代码:

import Airtable from "airtable";

const base: string = 'xxx'
const getClient = () => new Airtable({apiKey: 'xxx'});

export async function getAirtableData(): Promise<string[]> {
    return []
}

我的测试:

test('Airtable to ElasticSearch', async () => {
  expect(await getAirtableData()).toBe([])
});

但是当我运行测试(使用 Jest)时,出现以下错误:

TypeError: Cannot read property 'bind' of undefined

编辑:在不使用 Jest 的情况下使用 ts-node 手动运行代码就可以了。

Google 只返回与我没有使用的 React 相关的问题。可能是什么问题?

【问题讨论】:

  • 原代码是不是一模一样,原代码中是否涉及到“this”?
  • 这是原码,是的。报错就行了import Airtable from "airtable";我用的是airtable版本^0.10.1

标签: typescript jestjs


【解决方案1】:

我建议你看看你的打字稿配置,

以下对我有用:

tsconfig.json:

  "compilerOptions": {
    "lib": ["ES2019"],
    "target": "ES2019",
    "module": "commonjs",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

package.json:

{
  "devDependencies": {
    "@types/jest": "27.0.1",
    "airtable": "^0.10.1",
    "jest": "27.1.1",
    "ts-node": "10.2.1",
    "typescript": "4.4.3",
    "ts-jest": "27.0.5"
  }
}

jest.config.js:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

现在使用您的代码示例,我的main.ts

import Airtable from "airtable";

const base: string = 'xxx'
const getClient = () => new Airtable({apiKey: 'xxx'});

export async function getAirtableData(): Promise<string[]> {
    return []
}

main.test.ts:

import {getAirtableData} from './main'

test('Airtable to ElasticSearch', async () => {
  expect(await getAirtableData()).toEqual([])
});

它按预期工作:

【讨论】:

    猜你喜欢
    • 2021-10-08
    • 1970-01-01
    • 2022-06-16
    • 2020-12-23
    • 1970-01-01
    • 2021-03-28
    • 2019-05-05
    • 2020-06-09
    • 1970-01-01
    相关资源
    最近更新 更多