Śān*_*anu 6 reactjs react-native react-native-testing-library
我很难理解如何测试我的模态组件。我正在使用React-native-modals包和@testing-library/react-native和 Jest。我的组件是一个模式,当 GraphQL 错误传递给它时会弹出。
./ErrorMessage.js
import React from 'react';
import PropTypes from 'prop-types';
import { Dimensions, Text } from 'react-native';
import Modal, { ModalContent, ScaleAnimation } from 'react-native-modals';
import { theme } from '../styles/theme.styles';
const ModalError = ({ error, onClose }) => {
if (!error || !error.message) {
return (
<Modal visible={false}>
<Text />
</Modal>
);
}
return (
<Modal
visible
modalAnimation={
new ScaleAnimation({
initialValue: 0,
useNativeDriver: true,
})
}
onTouchOutside={onClose}
swipeDirection={['up', 'down', 'left', 'right']}
swipeThreshold={200}
onSwipeOut={onClose}
modalStyle={modalStyle}
overlayOpacity={0.7}
>
<ModalContent>
<Text testID="graphql-error">{error.message}</Text>
</ModalContent>
</Modal>
);
};
ModalError.defaultProps = {
error: {},
};
ModalError.propTypes = {
error: PropTypes.object,
onClose: PropTypes.func.isRequired,
};
export default ModalError;
const window = Dimensions.get('window');
const modalStyle = {
backgroundColor: theme.lightRed,
borderLeftWidth: 5,
borderLeftColor: theme.red,
width: window.width / 1.12,
};
Run Code Online (Sandbox Code Playgroud)
到目前为止我的测试非常简单。我只是想确保它正在渲染模式。我不太确定这里需要模拟什么或者如何做到这一点。
./__tests__/ErrorMessage.test.js
import React from 'react';
import { MockedProvider } from '@apollo/react-testing';
import { GraphQLError } from 'graphql';
import { render } from '@testing-library/react-native';
import Error from '../ErrorMessage';
jest.mock('react-native-modals', () => 'react-native-modals');
const error = new GraphQLError('This is a test error message.');
const handleOnCloseError = jest.fn();
describe('<ErrorMessage>', () => {
it('should render an ErrorMessage modal component', () => {
const { container } = render(
<MockedProvider>
<Error error={error} onClose={handleOnCloseError} />
</MockedProvider>
);
expect(container).toMatchSnapshot();
});
});
Run Code Online (Sandbox Code Playgroud)
我收到的错误是...
TypeError: _reactNativeModals.ScaleAnimation is not a constructor
18 | visible
19 | modalAnimation={
> 20 | new ScaleAnimation({
| ^
21 | initialValue: 0,
22 | useNativeDriver: true,
23 | })
Run Code Online (Sandbox Code Playgroud)
而且快照只是打印......
./__tests__/__snapshots__/ErrorMessage.test.js.snap
// Jest Snapshot v1,
exports[`<ErrorMessage> should render an ErrorMessage modal component 1`] = `
<View
collapsable={true}
pointerEvents="box-none"
style={
Object {
"flex": 1,
}
}
/>
`;
Run Code Online (Sandbox Code Playgroud)
我怎样才能克服这个错误并制作正确的快照?
当您这样做时jest.mock('react-native-modals', () => 'react-native-modals');,您将用字符串“react-native-modals”替换整个库,因此当您在组件中使用它时它会失败。您需要从模拟函数返回完整的模拟实现(jest.mock 的第二个参数)。自动模拟也可能对您有用,只需执行以下操作即可完成:jest.mock('react-native-modals');
以下是 jest.mock() 的扩展坞,其中包含一些使用它的各种方法的示例:https://jestjs.io/docs/en/jest-object#jestmockmodulename-factory-options。
| 归档时间: |
|
| 查看次数: |
8880 次 |
| 最近记录: |