Alp*_*ati 3 unit-testing async-await reactjs jestjs
我正在使用“ aws-amplify”库中的signIn方法。我在开玩笑地运行测试用例时无法从该库调用signIn方法。
码:
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 });
}
}
Run Code Online (Sandbox Code Playgroud)
测试文件:
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);
});
Run Code Online (Sandbox Code Playgroud)
在测试用例之上运行时,它总是进入handleSubmit()函数的catch部分。
如何实现从“ aws-amplify”库调用signIn方法并测试正/负方案?
指导我,谢谢。
小智 9
一种实现方法是模拟signIn函数并使用它。对于测试文件中的导入Auth
import { Auth } from "aws-amplify";
Run Code Online (Sandbox Code Playgroud)
然后在调用handleSubmit函数模拟signIn函数之前
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);
});
Run Code Online (Sandbox Code Playgroud)
我就是这样做的:
import awsAmplify from 'aws-amplify'
jest.mock('aws-amplify')
it('does something', () => {
awsAmplify.Auth.signIn.mockRejectedValue('mock error')
awsAmplify.Auth.currentAuthenticatedUser.mockResolvedValue('mock user')
...
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1852 次 |
最近记录: |