amazon-cognito-identity-js icon indicating copy to clipboard operation
amazon-cognito-identity-js copied to clipboard

Unit tests with cognito

Open sarah-pixvana opened this issue 8 years ago • 6 comments

I'm curious as to whether anyone has found success in writing unit tests that involve calls to cognito. I am consistently getting errors (coming from the aws-sdk) when I try to write unit tests.

sarah-pixvana avatar Sep 02 '16 00:09 sarah-pixvana

I suggest using mock-require or the like to mock out the functionality:

// sign-up-ui.test.js
// from memory, probably doesn't work!
import test from 'ava';
import mockRequire, { reRequire } from 'mock-require';

test('fails :: shows error', async t => {
  class MockCognitoUserPool {
    async signUp() {
      throw { code: "UserExistsException" };
    }
  }

  // When require() (including transpiled imports) tries to load the module from now
  // it will instead return the mock value: mockCognitoSDK
  const mockCognitoSDK = {
    CognitoUserPool: MockCognitoUserPool,
  };
  mockRequire('amazon-cognito-identity-js', mockCognitoSDK);

  // reRequire clears any cached sign-up-ui module so it uses the mock sdk
  const ui = reRequire('./sign-up-ui');

  await ui.signUp();
  t.is(ui.errorMessage, 'Username already exists, try another!');
});

I've been using this style with a lot of success in our project, and have started on a branch to test the cognito sdk

simonbuchan avatar Sep 02 '16 04:09 simonbuchan

Thanks I will give that a try :)

sarah-pixvana avatar Sep 02 '16 16:09 sarah-pixvana

@simonbuchan any chance you could expand on the process for testing functions that call the Cognito SDK methods?

I have auth functions in my web app that calls cognitoUser.authenticateUser() etc and I want to stub this out in my testing. However I'm pretty stuck and not sure how to approach it.

thchia avatar Dec 23 '16 03:12 thchia

It would be ideal if we could have a test code or if the signUp result object had a code on it...

Anyway.. I managed to test everything I could except confirmation. https://gist.github.com/wordyallen/3a8e28005d3563c91c1151037353e6a7

wordyallen avatar Sep 02 '17 21:09 wordyallen

@thchia Hey, did you manage to test cognitoUser.authenticateUser()?

nguyeti avatar Dec 16 '17 18:12 nguyeti

@nguyeti if you're talking about stubbing the functionality of this library, I suggest using a dependency injection pattern so you can easily mock it for your tests.

thchia avatar Dec 18 '17 11:12 thchia