首页 > 解决方案 > 使用反应测试库和 Jest 测试 Amplify Cognito Auth.SignIn()

问题描述

我有反应应用程序,允许用户注册然后从主页登录到我的应用程序(到仪表板组件)。现在我想测试我的应用程序。首先,我想测试我的登录和注销。

我对如何测试它的想法如下:

  1. 使用登录表单呈现主页
  2. 填写用户名和密码并点击登录按钮
  3. 检查仪表板中的一些文本
  4. 找到注销按钮并单击它
  5. 检查主页是否已呈现

问题在于登录是使用 AWS Cognito 用户池实现的,当仪表板应该呈现时,我const { attributes: { email, profile } } = await Auth.currentUserInfo(); attributes are undefined从仪表板组件中收到错误。我试图遵循这个答案,但这不起作用。

我还认为我可以通过在测试中首先调用 Auth.SignIn() 来消除这种情况,但我得到了这里Auth: Native crypto module could not be used to get a secure random number.讨论的错误。不幸的是,我无法解决这两个问题。你能解决我的问题或建议另一种更好的方法吗?

PS。我想await Auth.SignIn()工作,因为我会在仪表板的其他测试中使用它(我将渲染仪表板组件,然后从数据库发送/接收一些数据)。顺便提一句。Auth.SignIn()功能在反应应用程序中工作得很好。

test("sign out user", async () => {

    Amplify.configure(config);
    // await Auth.signIn(TEST_USERNAME, TEST_PASSWORD); // want this to work
    const history = useHistory();
    render(<Dashboard />);

    // sign out svg exists
    const logoutSvg = screen.getByTestId("logoutSvg");
    expect(logoutSvg).toBeInTheDocument();

    // click it
    await userEvent.click(logoutSvg);

    // wait for disaperance of the dashboard
    await waitFor(() => {
        expect(logoutSvg).not.toBeInTheDocument()
    })
        
    // check if home page is shown
    expect(screen.getByText(/Homepage/i)).toBeInTheDocument();
    expect(screen.getByText(/Log in/i)).toBeInTheDocument();

    // screen.debug();
})

聚苯乙烯。正确的使用方法是什么await waitFor(()=>{})。我的方法行不通。

我很乐意回答任何后续问题。非常感谢!

标签: reactjsjestjsamazon-cognitoaws-amplifyreact-testing-library

解决方案


推荐阅读