Jest React Native无法找到带有testd:的元素



我使用Jest来测试我的React Native应用程序,但我有很多麻烦。其中一个错误是:Unable to find an element with testID: loginButton

这是我的JSX代码:
<Button
testID="loginButton"
onPress={() => navigation.navigate('Home')}>
Join for free
</Button>

和测试代码:

import React from 'react';
import Login from '../screens/Login';
import {fireEvent, render} from '@testing-library/react-native';
describe('Login screen', () => {
it('should go to dashboard', () => {
const navigation = {navigate: () => {}};
jest.spyOn(navigation, 'navigate');

const page = render(<Login navigation={navigation} />);
const loginButton = page.getByTestId('loginButton');

fireEvent.press(loginButton);

expect(navigation.navigate).toHaveBeenCalledWith('Home');
});
});

编辑:如果我做const loginButton = page.queryAllByTestId('loginButton');测试通过。

我做错了什么?谢谢!

我忘了说我使用NativeBase和我的应用程序被包装在一个<NativeBaseProvider>。要解决上述问题,您可以简单地在测试中将initialWindowMetrics传递给NativeBaseProvider。

const inset = {
frame: { x: 0, y: 0, width: 0, height: 0 },
insets: { top: 0, left: 0, right: 0, bottom: 0 },
};
<NativeBaseProvider initialWindowMetrics={inset}>
{children}
</NativeBaseProvider>;

最新更新