我正在尝试使用以下内容测试具有 useEffect 钩子的屏幕:
export const SomeScreen: React.FC<Props> = ({}) => {
const [isSensorAvailable, setIsSensorAvailable] = useState(false);
useEffect(() => {
const isSensorAvailableCheck = async () => {
try {
await FingerprintScanner.isSensorAvailable();
setIsSensorAvailable(true);
} catch (error) {
console.log(error);
}
};
isSensorAvailableCheck();
}, []);
...
Here goes code that renders View if the sensor is available
...
}
我正在尝试以下测试:
import {default as FingerprintScannerMock} from 'react-native-fingerprint-scanner';
jest.mock('react-native-fingerprint-scanner');
(FingerprintScannerMock.isSensorAvailable as jest.Mock).mockResolvedValue(true);
const createTestProps = (props: Object) => ({
navigation: {
navigate: jest.fn(),
},
...props,
});
describe('Testing some screen', () => {
test('testing some functionalities', async () => {
let props: any;
props = createTestProps({});
const component = render(
<Provider store={store}>
<RegisterPasswordScreen {...props} />
</Provider>,
);
const {getByText, getByTestId, getAllByTestId} = component;
const container = getByTestId('containerId');
expect(container).toBeTruthy();
});
});
但是这个容器从来没有被找到,因为setIsSensorIsAvailable从来没有把值设置为true,因为下面的错误:
An update to SomeScreen inside a test was not wrapped in act(...).
我尝试了一切,甚至像这样:
const component = await waitFor(() =>
render(<Provider store={store}>
<RegisterPasswordScreen {...props} />
</Provider>,
);
);
但是当我运行这个测试时,它永远不会结束。还尝试用 act(...)
包装它,但这也不起作用,然后错误如下:
Can't access .root on unmounted test renderer
。
感谢任何帮助,谢谢!
答案 0 :(得分:0)
我最终使用了 findByTestId
而不是 getByTestId
,现在它运行良好。