【问题标题】:Jest Typescript class implementation - "... is not a function"Jest Typescript 类实现 - “...不是函数”
【发布时间】:2021-02-27 23:09:25
【问题描述】:

Jest 新手,所以我想了解一个我遇到的问题。我正在尝试在 Jest 中测试一个类的实现,但它抱怨我的函数“不是函数”

打字稿服务:

export class TestService {
    constructor() { }

    getAllData = async (): Promise<any> => {
        return { id: '1', name: 'test' }
    }
}

测试

import { TestService } from '../TestService';

describe('TestService', async () => {
   const service = new TestService();
   const res = await service.getAllData();

   ....
}

jest.config.ts 从“@jest/types”导入类型 {Config};

const config: Config.InitialOptions = {
  roots:['<rootDir>'],
    testMatch: [
    '**/__tests__/**/*.+(ts|tsx|js)',
    '**/?(*.)+(spec|test).+(ts|tsx|js)'
  ],
  testPathIgnorePatterns: ['dist', 'node_modules'],
  transform: {"\\.(ts|tsx)$": "ts-jest"},
  verbose: true,
  preset: 'ts-jest',
  testEnvironment: 'node',
  collectCoverage: true,
  automock: true
};

export default config;

当我运行测试时,Jest 抛出一个错误,上面写着“service.getAllData 不是函数”。我可以在网上找到的所有内容都指向模拟,但我认为我不想模拟这个,因为我想测试该类的实际实现;我假设我想模拟 getAllData() 中的任何外部函数。

我有一个控制器,它能够毫无问题地调用这个函数,所以我想知道是 1) 必须以其他方式调用它还是 2) Jest 本质上需要某种模拟。

如果您有任何见解,请告诉我

谢谢!

【问题讨论】:

  • 构造函数只是constructor()constructor() { }?
  • 哎呀,我的帖子中有错字。它是构造函数(){}。我会更新帖子

标签: javascript typescript unit-testing jestjs babeljs


【解决方案1】:

automock 是一种不好的做法,最好禁用。如果需要自动模拟模块,可以使用jest.mock 显式完成。大多数情况下,手动模拟更可取,因为它们会产生明确指定的实现,这些实现也应该额外提供给自动模拟。

Jest 自动模拟未记录在案,它会导致难以理解的魔法,可能无法满足开发人员的期望,并且可能会在下一个 Jest 版本中更改,恕不另行通知。 the guide 中简要描述了类自动模拟。 getAllData 是在构造函数中创建的实例方法。 Jest 自动模拟依赖于模块的运行时内容并检查静态和原型成员,它无法处理构造函数。

为了被 Jest 自动模拟检测到,getAllData 应该是原型方法,这也是常识建议的,因为它没有理由成为箭头:

export class TestService {
    getAllData(): Promise<any> {
        return { id: '1', name: 'test' }
    }
}

自动模拟不会产生正确的模拟,因为该方法是存根的,它不会返回一个承诺。这个问题可以在更早的时候确定,因为自动模拟需要指定一个实现,这在 OP 中没有完成:

const service = new TestService();
service.getAllData.mockResolvedValueOnce(...);
...

对于原型方法,这可以在实例可用之前完成:

TestService.prototype.getAllData.mockResolvedValueOnce(...);
const service = new TestService();
...

【讨论】:

    猜你喜欢
    • 2020-08-06
    • 2019-12-09
    • 1970-01-01
    • 2019-03-22
    • 2020-09-14
    • 2019-10-01
    • 2019-03-28
    • 2021-03-11
    • 1970-01-01
    相关资源
    最近更新 更多