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

How to stub a static function in an abstract class | typescript

我在测试此功能时遇到了真正的麻烦 Client.read.pk(string).sk(string)。我创建这个 class 是为了简化使用 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不支持stub standalone function和class constructor(DocumentClient class) import from a module,所以需要使用link seams. we will be using 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 |                   
-----------|---------|----------|---------|---------|-------------------