如何在玩笑中模拟 AWS 库 [英] how to mock AWS library in jest

查看:20
本文介绍了如何在玩笑中模拟 AWS 库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用aws-amplify"库中的 signIn 方法.在玩笑中运行测试用例时,我无法从该库调用 signIn 方法.

I am using signIn method from 'aws-amplify' library. I am not able to call signIn method from this library while running test case in jest.

代码:

import { Auth } from "aws-amplify"; // import statement

//code for function
handleSubmit = async event => {
  event.preventDefault();
  this.setState({ isLoading: true });
  try {
    await Auth.signIn(this.state.username, this.state.password);
    this.props.history.push("/dashboard");
  } catch (e) {
    this.setState({ isLoading: false });
  }
}

测试文件:

it('calls event handler; "handleSubmit"', async()  => {   
    const componentInstance = Wrapper2.dive().instance();

    componentInstance.setState({
        isLoading : false,
        username : "demo",
        password : "demo"
    })
    const event = {
        preventDefault : () => {}
    };
    await componentInstance.handleSubmit(event);
    expect(componentInstance.state.isLoading).toEqual(true); 
});

在测试用例上面运行时,它总是进入handleSubmit()函数的catch部分.

While running above test case, It always goes into catch section of handleSubmit() function.

如何实现从 'aws-amplify' 库调用 signIn 方法并测试正面/负面场景?

How can I achieve calling signIn method from 'aws-amplify' library and testing positive/negative scenarios ?

请指导我,提前致谢.

推荐答案

一种方法是模拟 signIn 函数并使用它.对于测试文件中的导入身份验证

One way to do this is mocking signIn function and using it. For that import Auth in test file

import { Auth } from "aws-amplify";

然后在调用handleSubmit函数之前模拟signIn函数

then before calling handleSubmit function mock signIn function

it('calls event handler; "handleSubmit"', async()  => {   
    const componentInstance = Wrapper2.dive().instance();

    componentInstance.setState({
        isLoading : false,
        username : "demo",
        password : "demo"
    })
    const event = {
        preventDefault : () => {}
    };
    Auth.signIn = jest.fn().mockImplementation(
     () => {
     // return whatever you want to test
    });
    await componentInstance.handleSubmit(event);
    expect(componentInstance.state.isLoading).toEqual(true); 
});

这篇关于如何在玩笑中模拟 AWS 库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆