Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Jest类型脚本类实现-“;。。。不是一个函数;_Javascript_Typescript_Unit Testing_Jestjs_Babeljs - Fatal编程技术网

Javascript Jest类型脚本类实现-“;。。。不是一个函数;

Javascript Jest类型脚本类实现-“;。。。不是一个函数;,javascript,typescript,unit-testing,jestjs,babeljs,Javascript,Typescript,Unit Testing,Jestjs,Babeljs,我不喜欢开玩笑,所以我想更好地理解一个问题。我试着开玩笑地测试一个类的实现,但它抱怨我的函数“不是函数” 类型脚本服务: export class TestService { constructor() { } getAllData = async (): Promise<any> => { return { id: '1', name: 'test' } } } jest.config.ts 从'@jest/types'导入类型{C

我不喜欢开玩笑,所以我想更好地理解一个问题。我试着开玩笑地测试一个类的实现,但它抱怨我的函数“不是函数”

类型脚本服务:

export class TestService {
    constructor() { }

    getAllData = async (): Promise<any> => {
        return { id: '1', name: 'test' }
    }
}
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;
const-config:config.InitialOptions={
根:[''],
测试匹配:[
“**/\\\\\\/**.+(ts | tsx | js)”,
“***/?(*)+(规范测试)。+(ts | tsx | js)”
],
testPathIgnorePatterns:['dist','node_modules'],
转换:{“\\(ts | tsx)$”:“ts jest”},
没错,
预设:“ts笑话”,
测试环境:“节点”,
报道:是的,
automock:对
};
导出默认配置;
当我运行测试时,Jest抛出了一个错误,上面写着“service.getAllData不是函数”。我能在网上找到的所有东西都指向mock,但我不认为我会想模仿它,因为我想测试类的实际实现;我假设我想模拟
getAllData()
中的任何外部函数

我有一个控制器,可以毫无问题地调用这个函数,所以我想知道1)是否有其他方法必须调用这个函数,或者2)Jest本质上需要某种模拟

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


谢谢

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

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

为了通过Jest自动模拟进行检测,
getAllData
应该是原型方法,这也是常识所建议的,因为没有理由将其作为箭头:

export class TestService {
    getAllData(): Promise<any> {
        return { id: '1', name: 'test' }
    }
}
对于原型方法,这可以在实例可用之前完成:

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

构造函数就是
constructor()
或者
constructor(){}
?哎哟,我的帖子打错了。它是构造函数(){}。我会更新帖子的
const service = new TestService();
service.getAllData.mockResolvedValueOnce(...);
...
TestService.prototype.getAllData.mockResolvedValueOnce(...);
const service = new TestService();
...