amazon-cognito-identity-js
amazon-cognito-identity-js copied to clipboard
Unit tests with cognito
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.
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
Thanks I will give that a try :)
@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.
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
@thchia Hey, did you manage to test cognitoUser.authenticateUser()
?
@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.