0

My index.ts file looks like this

import {IS3Client, S3Client} from './client/S3Client';
const s3: IS3Client = new S3Client();

export async function someFunc(event: any, context: any, callback: any) {

  const x: string = await s3.getFile('a','b');

}

S3Client.ts looks like this

import * as AWS from 'aws-sdk';

export interface IS3Client {
    getFile(bucketName: string, fileName: string): Promise<any>;
}

export class S3Client implements IS3Client {
    private s3Client: AWS.S3;

    constructor() {
        this.s3Client = new AWS.S3();
    }

    public async getFile(bucketName: string, fileName: string): Promise<any> {
        const params = {
            Bucket: bucketName,
            Key: fileName,
        };
        return (await this.s3Client.getObject(params).promise()).Body.toString();
    }
}

Now I am interested to mock the getFile function to return what I want when I am testing index.ts

My test case looks like this

import {someFunc} from '../src/index';
import { S3Client } from '../src/client/S3Client';

describe("Test Suite", () => {
  beforeAll(()=>{
    jest.mock('../src/client/S3Client');
    const mockedClient: jest.Mocked<S3Client> = new S3Client() as any;
    mockedClient.getFile.mockImplementation(() => Promise.resolve('hello'));
  });
  it("testCase", () => {
    const req = {
      "key" : ["value"]
    };
    someFunc(req, null, null);
  })
});

I am getting the following error :

TypeError: mockedClient.getFile.mockImplementation is not a function

Somehow this is looking much harder than I thought. Can someone suggest something, Thanks in advance ?

I added another class like this

import { SecretsManager } from 'aws-sdk';

export default class XUtils {
    private secretsManager: SecretsManager;

    constructor(secretsManager: SecretsManager) {
        this.secretsManager = secretsManager;
    }

    public async getData(urlPrefix: string): Promise<any[]> {
        return ['data'];
    }
}

And my index.ts looks something like this :

import {IS3Client, S3Client} from './client/S3Client';
import XUtils from './utils/XUtils';
import { SecretsManager } from 'aws-sdk';

const s3: IS3Client = new S3Client();
const secretsManager: SecretsManager = new SecretsManager({ region: process.env.AWS_REGION });
const xUtils: XUtils = new XUtils(secretsManager)

export async function someFunc(event: any, context: any, callback: any) {

  const x: string = await s3.getFile('a','b');
  const y = await xUtils.getData(x);
}

Following from what you suggested, I modified my test case to something like this :

import {someFunc} from '../src/index';
import { S3Client } from '../src/client/S3Client';
import XUtils from '../utils/XUtils';

jest.mock('../src/client/S3Client', () => {
  const mS3Client = { getFile: jest.fn() };
  return { S3Client: jest.fn(() => mS3Client) };
});

jest.mock('../utils/XUtils', () => {
  const mXUtils = { getData: jest.fn() };
  return { XUtils: jest.fn(() => mXUtils) };
});

describe("Test Suite", () => {
  beforeAll(()=>{
    mockedClient = new S3Client() as any;
    mockedClient.getFile.mockImplementation(() => Promise.resolve('url'));

    mockedXUtils = new XUtils(null) as any;
    mockedXUtils.getData.mockImplementation(() => Promise.resolve(['data']))
  });
  it("testCase", () => {
    const req = {
      "key" : ["value"]
    };
    someFunc(req, null, null);
  })
});

I am getting error now as

TypeError: XUtils_1.default is not a constructor

What exactly is this problem ?

1 Answers1

1
  1. You can't use jest.mock in the function scope. It should be used in module scope.
  2. You should use async/await for someFunc method in your test case.

E.g.

index.ts:

import { IS3Client, S3Client } from './s3client';
const s3: IS3Client = new S3Client();

export async function someFunc(event: any, context: any, callback: any) {
  const x: string = await s3.getFile('a', 'b');
}

s3client.ts:

import * as AWS from 'aws-sdk';

export interface IS3Client {
  getFile(bucketName: string, fileName: string): Promise<any>;
}

export class S3Client implements IS3Client {
  private s3Client: AWS.S3;

  constructor() {
    this.s3Client = new AWS.S3();
  }

  public async getFile(bucketName: string, fileName: string): Promise<any> {
    const params = {
      Bucket: bucketName,
      Key: fileName,
    };
    return (await this.s3Client.getObject(params).promise()).Body!.toString();
  }
}

index.test.ts:

import { someFunc } from './';
import { S3Client } from './s3client';

jest.mock('./s3client', () => {
  const mS3Client = { getFile: jest.fn() };
  return { S3Client: jest.fn(() => mS3Client) };
});

describe('Test Suite', () => {
  let mockedClient: jest.Mocked<S3Client>;
  beforeAll(() => {
    mockedClient = new S3Client() as any;
    mockedClient.getFile.mockImplementation(() => Promise.resolve('hello'));
  });
  it('testCase', async () => {
    const req = {
      key: ['value'],
    };
    await someFunc(req, null, null);
    expect(mockedClient.getFile).toBeCalledWith('a', 'b');
  });
});

Unit test results with 100% coverage:

 PASS  stackoverflow/60445082/index.test.ts (8.548s)
  Test Suite
    ✓ testCase (6ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.ts |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.04s

source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60445082

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • Whatever u suggested worked, but I added a new class and tried to modify the test case, and it failed. I have added details onto the question. can you check once ? – Dark Shadows Feb 28 '20 at 19:52