Testing AWS Cognito from Jest fails, but the same code in a component works

Viewed 1125

I am trying to integration test my react components. I need a valid JWT token to call the APIs to get the data to render the tables to test the components and interactions. It's about a million times easier (in theory) to just do this with a jest test that try to mock the whole of the universe, so I'm not very interested in mocking. I could use a browser test I suppose, but they always seem to be pretty flaky so I'd rather use a jest integration test.

Problem is, despite having the same exact code; when I run it as a jest test it fails, and when I run it in a react component, it works. Same credentials; same code. I keep looking for what context I'm missing somehow; but I'm not seeing anything sticking out.

I have the following test:

    it('calls cognito library', async() => {
        const poolData = {
            UserPoolId: awsconfig.aws_user_pools_id,
            ClientId: awsconfig.aws_user_pools_web_client_id
        };

        const userPool = new CognitoUserPool(poolData);
        const authenticationData = {
            Username: "myuserhere@example.com",
            Password: "mypassword123#",
        };
        const authenticationDetails = new AuthenticationDetails(
            authenticationData
        );
        const userData = {
            Username: "myuserhere@example.com",
            Pool: userPool
        };
        console.log("attempting sign in to ", userData, authenticationData)
        const cognitoUser = new CognitoUser(userData);
        return new Promise<CognitoUserSession>((resolve, reject) => {
            cognitoUser.authenticateUser(authenticationDetails, {
                onSuccess: function (result) {
                    resolve(result)
                },

                newPasswordRequired: () => {
                    reject("NEW PASSWORD REQUIRED");
                },

                onFailure: function (err) {
                    reject(err);
                },
            })
        })
    })

and the following JSX component:

import React, {useEffect} from 'react'
import {useState} from 'react'
import awsconfig from "./conf/aws-exports";
import {AuthenticationDetails, CognitoUser, CognitoUserPool, CognitoUserSession} from "amazon-cognito-identity-js";

export const TestMe = () => {

    const [auth, setAuth] = useState<boolean>(false)

    const poolData = {
        UserPoolId: awsconfig.aws_user_pools_id, 
        ClientId: awsconfig.aws_user_pools_web_client_id
    };

    const userPool = new CognitoUserPool(poolData);
    const authenticationData = {
        Username: "myuserhere@example.com",
        Password: "password123#",
    };
    const authenticationDetails = new AuthenticationDetails(
        authenticationData
    );
    const userData = {
        Username: "myuserhere@example.com",
        Pool: userPool
    };
    const cognitoUser = new CognitoUser(userData);

    useEffect(() => {
        console.log("attempting sign in to ", userData, authenticationData)
        new Promise<CognitoUserSession>((resolve, reject) => {
            cognitoUser.authenticateUser(authenticationDetails, {
                onSuccess: function (result) {
                    resolve(result)
                },

                newPasswordRequired: () => {
                    reject("NEW PASSWORD REQUIRED");
                },

                onFailure: function (err) {
                    reject(err);
                },
            })
        }).then(() => {
            setAuth(true)
        })
    }, [])

    return (
        <div>{auth ? "Yes" : "No"}</div>
    )
}

and the following index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.css';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import {TestMe} from "./TestMe";

ReactDOM.render(
    <Router>
        <TestMe />
    </Router>
    , document.getElementById('root'));

serviceWorker.unregister();

I was originally using amplify, but had so many problems, I chucked it out and kept only the config file. How can I make the jest test work and authenticate?

1 Answers
Related