问题
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