首页 > 解决方案 > Jest TypeError:无法读取未定义的属性“绑定”

问题描述

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

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

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

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

标签: typescriptjestjs

解决方案


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

以下对我有用:

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([])
});

它按预期工作:

在此处输入图像描述


推荐阅读