3
\$\begingroup\$

I've wrapped an imported function (a promise) and attempted to write unit tests that bring my codebase to 100% coverage.

import { Auth } from 'aws-amplify';

import signIn from './shared';

describe('signIn', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });

  it('invokes the success callback on success', (done) => {
    const mockUser = { username: 'jon', password: 'snow' };

    jest
      .spyOn(Auth, 'signIn')
      .mockImplementation(() => Promise.resolve(mockUser));

    const mockSuccessCb = (user) => {
      expect(user).toBe(mockUser);
      done();
    };

    const mockErrorCb = (err) => {
      done(err);
    };

    signIn('jon', 'snow', mockSuccessCb, mockErrorCb);
  });

  it('invokes the error callback on err', (done) => {
    const mockUser = { username: 'jon', password: 'snow' };

    jest
      .spyOn(Auth, 'signIn')
      .mockImplementation(() => Promise.reject(mockUser));

    const mockSuccessCb = (user) => {
      expect(Auth.signIn).toHaveBeenCalledWith('jon', 'snow');
      expect(user).toBe(mockUser);
      done();
    };

    const mockErrorCb = () => {
      expect(Auth.signIn).toHaveBeenCalledWith('bob', 'tom');
      done();
    };

    signIn('bob', 'tom', mockSuccessCb, mockErrorCb);
  });
});

Auth is the imported object that is getting wrapped. In my first test, I attempt verify a successful login by returning a resolved promise. In the second test, I reject the promise. I got my 100% coverage, but since I tell my promise how to resolve itself, I can't help but feel like I'm setting myself up for false positives. Is this a good test? How can it be improved?

Edit: Added the original wrapper function for detail:

import { Auth } from 'aws-amplify';

const signIn = (
  username,
  password,
  successCallback,
  errorCallback,
) => {
  Auth.signIn(username, password)
    .then(user => successCallback(user))
    .catch(err => errorCallback(err));
};

export default signIn;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.