how to mock AWS library in jest

*爱你&永不变心* 提交于 2020-05-13 11:05:06

问题


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.

Code:

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 });
  }
}

Test file:

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); 
});

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

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

Guide me, Thanks in advance.


回答1:


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

import { Auth } from "aws-amplify";

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); 
});



回答2:


This is how I did it:

import awsAmplify from 'aws-amplify'

jest.mock('aws-amplify')

it('does something', ()  => {
  awsAmplify.Auth.signIn.mockRejectedValue('mock error')
  awsAmplify.Auth.currentAuthenticatedUser.mockResolvedValue('mock user')
  ...
})



来源:https://stackoverflow.com/questions/51649891/how-to-mock-aws-library-in-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!