typescript - 如何在抽象类中存根静态函数 打字稿
问题描述
我在测试这个功能时遇到了真正的麻烦Client.read.pk(string).sk(string)
。我创建了这个类来简化使用 dynamoDB 的 sdk 的过程,但是当我想对这个方法进行单元测试时,我似乎无法刺伤它!十分感谢你的帮助!
代码:
export abstract class Client {
static read = {
pk: (pk: string) => {
return {
sk: async (sk: string) => {
return await new DocumentClient()
.get({
TableName: "TodoApp",
Key: {
PK: pk,
SK: sk,
},
})
.promise();
},
};
},
};
}
解决方案
由于 Sinon 不支持DocumentClient
从模块导入的 stub 独立函数和类构造函数(类),因此您需要使用链接接缝。我们将使用proxyquire来构建我们的接缝。
例如
Client.ts
:
import { DocumentClient } from 'aws-sdk/clients/dynamodb';
export abstract class Client {
static read = {
pk: (pk: string) => {
return {
sk: async (sk: string) => {
return await new DocumentClient()
.get({
TableName: 'TodoApp',
Key: {
PK: pk,
SK: sk,
},
})
.promise();
},
};
},
};
}
Client.test.ts
:
import proxyquire from 'proxyquire';
import sinon from 'sinon';
describe('68430781', () => {
it('should pass', async () => {
const documentClientInstanceStub = {
get: sinon.stub().returnsThis(),
promise: sinon.stub().resolves('mocked data'),
};
const DocumentClientStub = sinon.stub().callsFake(() => documentClientInstanceStub);
const { Client } = proxyquire('./Client', {
'aws-sdk/clients/dynamodb': { DocumentClient: DocumentClientStub },
});
const actual = await Client.read.pk('a').sk('b');
sinon.assert.match(actual, 'mocked data');
sinon.assert.calledOnce(DocumentClientStub);
sinon.assert.calledWithExactly(documentClientInstanceStub.get, {
TableName: 'TodoApp',
Key: {
PK: 'a',
SK: 'b',
},
});
sinon.assert.calledOnce(documentClientInstanceStub.promise);
});
});
单元测试结果:
68430781
✓ should pass (435ms)
1 passing (439ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
Client.ts | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
推荐阅读
- node.js - 用户输入nodeJs的卫生 - Express
- javascript - 为欧洲(EU)用户加载 JS 文件
- python - 如何在不改变颜色的情况下从 RGB numpy 数组转换为 PIL 图像
- ios - iOS Metal Invalid device store执行顶点函数“myFunction”编码器:draw:offset:
- nlp - 使用 BERT 等预训练模型进行文档分类
- javascript - 如何在 javascript 中将 JSON 文件转换为数组?
- python - 如何处理节点字符串以获取它们的连接?
- vba - 如何禁用更改事件
- flutter - Flutter在Column中设置容器高度以适应
- c# - ASP.NET Core Web 应用程序 + 服务:自动化部署