When it comes to Sinon not supporting the stub standalone function and imported class constructor DocumentClient
, you'll need to rely on using link seams. In this case, we will utilize proxyquire for constructing our seams.
For example:
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);
});
});
Unit test result:
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 |
-----------|---------|----------|---------|---------|-------------------