【发布时间】:2018-09-16 02:58:25
【问题描述】:
我正在尝试(使用 Jest)对使用摘要类的处理程序模块进行单元测试。
我原来的总结类是这样的:
import DynamoDBClient from './ddbClient/DynamoDBClient'
import { DynamoDB } from 'aws-sdk'
import { iSummaryReader, iObsSummariesAttributes } from './Summary.d'
import { JSONAPIResource } from '../JSONAPIResponse'
export default class Summary {
reader: iSummaryReader
constructor(reader: iSummaryReader) {
this.reader = reader
}
getSummary = async (keyName: string, keyValue: string): Promise<JSONAPIResource<iObsSummariesAttributes>> => {
return new Promise<JSONAPIResource<iObsSummariesAttributes>>((resolve, reject) => {
const gettingItem = this.reader.getItem(keyName, keyValue)
console.log(gettingItem)
gettingItem.then((resp) => {
resolve(resp)
}).catch((err: Error) => {
reject(err.message)
})
})
}
}
在我的处理程序模块中,我使用import Summary from './lib/Summary' 导入
(注意:handler.test.ts中使用同一行
处理函数内部
try {
const dynamodbObj: iSummaryReader = new DynamoDBClient(documentClient, someTable)
const summary = new Summary(dynamodbObj)
const data: JSONAPIResource<iObsSummariesAttributes> = await summary.getSummary('id', someID)
}
如果尝试自动模拟,我的结果取决于我的方法
jest.mock('./lib/Summary', () =>
{
return {
getSummary: jest.fn()
}
})
我得到了错误
TypeError: Summary_1.default 不是构造函数
如果我在lib/__mocks__/Summary.ts 下使用jest.mock('./lib/Summary') 创建手动模拟,它确实可以工作,直到我明白这一点
expect(Summary).toHaveBeenCalledTimes(1)
它抱怨我无法在摘要中执行此操作。我也无法访问我的方法来测试它们是否以这种方式被调用。
注意:我的处理程序是针对 lambda 函数的,因此我无法以成功测试可以模拟注入的类的方式注入类。
编辑
tsconfig.json 是:
{
"compilerOptions": {
"rootDir": "./src",
"outDir": "./build",
"declaration": false,
"target": "es2015",
"moduleResolution": "node",
"module": "commonjs",
"noImplicitReturns": true,
"noImplicitThis": true,
"strictNullChecks": true,
"alwaysStrict": true,
"lib": [
"dom",
"es2015.promise",
"es2017.object",
"es2016"
],
},
"include": [
"src/**/*.ts"
],
}
【问题讨论】:
-
肯定和tsconfig.json文件有关。您可以在其中发布配置设置,它的位置吗?
-
在模拟模块时不需要模拟名为
default的导出吗?我不知道,因为我没有使用 jest,但我想如果你不使用它会完全模棱两可,并且框架可能假设你正在尝试模拟模块命名空间对象,因为这是唯一不模棱两可的解释 -
@AluanHaddad 我正在密切关注 jest 文档中提供的示例,该示例以这种方式进行 facebook.github.io/jest/docs/en/es6-class-mocks.html,我假设问题与打字稿的导入方式有关。
-
@user3559247 确保使用 TypeScript 的
--esModuleInterop标志和最新的语言版本。 TypeScript 现在以标准方式提供导入互操作,行为类似于 Babel 和 SystemJS。但是,鉴于您拥有的是default,无论如何它不应该有所作为,但是使用这些设置将允许您编写正确且符合标准的代码,而无需依赖其他可能不容易在之间移植的转换器和加载器测试环境和浏览器
标签: class typescript mocking jestjs