如何在抽象类中存根静态函数 |打字稿

时间:2021-07-18 15:54:48

标签: typescript mocha.js tdd chai sinon

我在测试此函数 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();
        },
      };
    },
  };
}

1 个答案:

答案 0 :(得分:1)

由于 Sinon 不支持从模块导入的存根独立函数和类构造函数(DocumentClient 类),因此您需要使用 link seams。我们将使用 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 |                   
-----------|---------|----------|---------|---------|-------------------