首页 > 解决方案 > 如何在抽象类中存根静态函数 打字稿

问题描述

我在测试这个功能时遇到了真正的麻烦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();
        },
      };
    },
  };
}

标签: typescriptmocha.jstddchaisinon

解决方案


由于 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 |                   
-----------|---------|----------|---------|---------|-------------------

推荐阅读