这里有一个如下所示的withPermissions HOC组件
export function withPermissions<T>(
WrappedComponent: React.ComponentType<T>,
requestedPermissions: RequestedPermissions,
) {
return class WithPermissions extends React.Component<
WithPermissionsProps & T,
WithPermissionsState
> {
readonly state: WithPermissionsState;
constructor(props: WithPermissionsProps & T) {
super(props);
this.state = {
focusSubscription: undefined,
permissions: {},
};
}
readonly checkPermissions = async () => {
const { permissions } = await Permissions.askAsync(...requestedPermissions);
const nextPermissions: RecievedPermissions = Object.entries(permissions).reduce(
(allPermissions, [permissionType, value]) => ({
...allPermissions,
[permissionType]: value.status,
}),
{},
);
this.setState(state => ({ ...state, permissions: nextPermissions }));
};
componentWillMount() {
this.checkPermissions();
}
render() {
const { permissions } = this.state;
return <WrappedComponent permissions={permissions} {...(this.props as T)} />;
}
};
}
我用HOC包裹了屏幕
export const ScanScreen = withPermissions<ScanScreenProps>(component, [
Permissions.CAMERA,
]);
我的测试代码如下
.mock("expo-permissions", () => ({
Permissions: {
askAsync: jest.fn(),
},
}));
test("Correct permissions are asked for in scanner screen", async () => {
const { environment } = renderWithPermissions(ScanScreen);
await resolveMostRecentOperation<CompleteScanScreenQuery>(environment);
Permissions.askAsync(Permissions.CAMERA);
});
当我尝试使用上面的代码时,出现以下错误
TypeError: Permissions.askAsync is not a function
当我将模拟从博览会许可更改为以下博览会
.mock("expo", () => ({
Permissions: {
askAsync: jest.fn(),
},
}));
const { environment } = renderWithPermissions(ScanScreen);
await resolveMostRecentOperation<CompleteScanScreenQuery>(environment);
Permissions.askAsync(Permissions.CAMERA); //undefined
错误将消失并且测试通过,但结果不确定
我尝试了以下代码,但无法渲染BarCodeScanner
test("Correct permissions are asked for in scanner screen", async () => {
const { environment, getByTestId } = renderWithPermissions(ScanScreen);
await resolveMostRecentOperation<CompleteScreenQuery>(environment);
const permissionsSpy = jest.spyOn(Permissions, "askAsync");
Permissions.askAsync(Permissions.CAMERA);
expect(permissionsSpy).toHaveBeenCalledWith(Permissions.CAMERA);
getByTestId("barCodeScanner");
});
错误
Unable to find an element with the testID of: barCodeScanner
我不确定该怎么做。有人可以帮帮我吗