我在react-native
使用expo时有下面的代码,这是一个按钮,单击button
将调用ImagePicker.requestMediaLibraryPermissionsAsync()
,如果授予权限,则调用ImagePicker.launchImageLibraryAsync()
以让用户选择图像。
我使用 React-native-testing-libary。
这段代码工作正常,但我开玩笑的测试一直失败,我在下面告诉它失败的地方。
这是我的测试,首先我expo-image-picker
使用上面提到的 2 个函数及其解析值来模拟模块:
import * as ImagePicker from 'expo-image-picker';
jest.mock('expo-image-picker', () => {
return {
requestMediaLibraryPermissionsAsync: jest.fn().mockResolvedValueOnce({
status: 'granted'
}),
launchImageLibraryAsync: jest.fn().mockResolvedValue({
cancelled: false, type: 'image',
uri: 'abc.jpeg',
width: '200',
height: '200'
})
}
})
这是我的代码供您参考:
import * as ImagePicker from 'expo-image-picker';
const requestPermission = async () => {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
alert('Sorry, we need camera roll permissions to make this work!');
}else{
pickImage()
}
}
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(result);
if (!result.cancelled) {
setImage(result.uri);
}
};
<Button title="Pick an image from camera roll" onPress={requestPermission} />
然后这是我在测试用例中所做的。
it('should pass test case ', () => {
const {getByTestId, queryByTestId, getByText} = render(<MyComponent />)
const pickImageButton = getByTestId('add_image')
// trigger the button
fireEvent.press(pickImageButton)
// request permission, here the resolved value is granted.
expect(ImagePicker.requestMediaLibraryPermissionsAsync).toBeCalledTimes(1)// here is pass
// choose from library this should be called
expect(ImagePicker.launchImageLibraryAsync).toBeCalledTimes(1) // test keep failing here
... other stuff here
})
如您所见,在我的测试用例中,它会触发一个按钮,然后调用ImagePicker.requestMediaLibraryPermissionsAsync
它来解决status: 'granted'
,这与我的代码相同。
既然status:granted
,那么这个函数ImagePicker.launchImageLibraryAsync()
应该被调用。
但是现在,expect(ImagePicker.requestMediaLibraryPermissionsAsync).toBeCalledTimes(1)
是pass,但是这条线 expect(ImagePicker.launchImageLibraryAsync).toBeCalledTimes(1)
不是pass。
我试过的:
我都试过了,expect
我把它包装在这样的里面waitFor()
:
// request permission
await waitFor(() => expect(ImagePicker.requestMediaLibraryPermissionsAsync).toBeCalledTimes(1))
// choose from library, this line never called.
await waitFor(() => expect(ImagePicker.launchImageLibraryAsync).toBeCalledTimes(1))
但是错误仍然相同,launchImageLibraryAsync()
永远不会被调用。
问题:
什么原因导致
launchImageLibraryAsync()
没有被调用?以及如何解决这个问题。我想我需要等待
requestMediaLibraryPermissionsAsync
完成解决,然后才会launchImageLibraryAsync()
被调用。但我该怎么做呢?如您所见,我已经用 包装了它waitFor()
,但错误仍然存在。