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

查看:93
本文介绍了如何在玩笑中模拟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函数并使用它. 对于测试文件中的导入Auth

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函数模拟登录函数之前

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天全站免登陆