1

I'm fairly new to angular and also to jest. I have a class like this:

import {CloudWatchLogs} from 'aws-sdk/clients/browser_default';
import {isNullOrUndefined} from 'util';

@Injectable()
export class MyService {

  private cloudWatchLogs: CloudWatchLogs = null;

  constructor() {}

  startService() {
    setupService();
    myOtherTask();
  }

  private setUpService() {

    if (!isNullOrUndefined(this.cloudWatchLogs)) {

      this.cloudWatchLogs = new CloudWatchLogs();
      // setup options
    }
  }

  private void myOtherTask() {

    this.cloudWatchLogs.doSomething();
    this.cloudWatchLogs.doSomethingElse();

  }
}

and i'm trying use Jest to run unit tests against MyService. What i'd like to know is, is it possible to mock the CloudWatchLogs methods for doSomething and doSomethingElse with the way this class has been written as it is, bearing in mind that CloudWatchLogs is a javascript object, and not an angular injectable.

The only solution i can see to being able to mock CloudWatchLogs is to create an injectable service that wraps the CloudWatchLogs, and then injecting this into MyService.

3
  • check this for service mock stackoverflow.com/a/49842183/4399281 Commented Apr 20, 2018 at 14:15
  • Your current code has the cloudWatchLogs as private in the service. An external test will not be able to view the contents to test what is happening. Consider modifying the code for testing, or dependency injection to be able to view the contents of cloudWatchLogs. As you are importing the CloudWatchLogs, this can be replaced with a Jest mock to set the contents for your test, but the private variable reference will stop an external test from being able to check the variable. Commented Apr 20, 2018 at 17:11
  • Thanks, that makes sense. Would it be possible for you to show me how to replace with a Jest mock, and set the contents? Commented Apr 20, 2018 at 19:30

1 Answer 1

0

So the way to do this was to do the following:

const mockDoSomething = jest.fn();
const mockDoSomethingElse = jest.fn();
jest.mock('aws-sdk/clients/cloudwatchlogs', () => {
  return jest.fn().mockImplementation(() => {
    return {
      doSomething: mockDoSomething,
      doSomethingElse: mockDoSomethingElse
    };
  });
});

and then in each test can mock the return values, e.g.

 const myReturnValue = 'whatever';
 mockDoSomething.mockReturnValueOnce(myReturnValue);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.