【发布时间】:2021-02-16 18:56:27
【问题描述】:
我正在尝试集成测试我的反应组件。我需要一个有效的 JWT 令牌来调用 API 以获取数据以呈现表格以测试组件和交互。通过一个试图模拟整个宇宙的笑话测试来做到这一点(理论上)要容易一百万倍,所以我对模拟不是很感兴趣。我想我可以使用浏览器测试,但它们似乎总是很不稳定,所以我宁愿使用开玩笑的集成测试。
问题是,尽管代码完全相同;当我将它作为开玩笑测试运行时它失败了,当我在反应组件中运行它时它可以工作。相同的凭据;相同的代码。我一直在寻找我错过了什么背景;但我没有看到任何突出的地方。
我有以下测试:
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);
},
})
})
})
以及以下 JSX 组件:
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>
)
}
和下面的 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();
我最初使用的是 amplify,但遇到了很多问题,我把它扔掉了,只保留了配置文件。如何使 Jest 测试工作并进行身份验证?
【问题讨论】:
标签: javascript reactjs typescript jestjs amazon-cognito