我在我的应用程序中使用了这个二维码扫描仪,但是在二维码扫描仪上进行单元测试时遇到了麻烦。如何在这个 qr 扫描仪上进行单元测试?我应该嘲笑它还是有办法将值发送到 onRead 道具?
之前,我曾尝试使用此代码模拟 react-native-qrcode-scanner
jest.mock('react-native-qrcode-scanner', () => {
const React = require('react');
const PropTypes = require('prop-types');
return class MockQRCodeScanner extends React.Component {
static propTypes = { children: PropTypes.any };
static defaultProps = { reactivate: false }
render() {
return React.createElement('react-native-qrcode-scanner', this.props, this.props.children);
}
}
})
但给出错误“TypeError:scanner.current.reactivate is not a function”
这是我的代码:ScanQRCodeScreen.js
'use strict';
import React, {useEffect} from 'react';
import {
View,
StyleSheet
} from 'react-native';
import QRCodeScanner from 'react-native-qrcode-scanner';
const ScanQRCodeScreen = ({navigation}) => {
const scanner = React.useRef(null);
useEffect(() => {
navigation.addListener('focus', async() => {
await scanner.current.reactivate();
});
},[]);
const onSuccess = e => {
console.log(e.data);
}
return (
<View>
<QRCodeScanner
onRead={onSuccess}
ref={scanner}
showMarker={true}
/>
</View>
);
};
扫描QRCodeScreen-test.js
import React, {useRef} from 'react';
import { render, act } from '@testing-library/react-native';
import ScanQRCodeScreen from '../screens/ScanQRCodeScreen';
jest.mock('react-native-qrcode-scanner', () => {
const React = require('react');
const PropTypes = require('prop-types');
return class MockQRCodeScanner extends React.Component {
static propTypes = { children: PropTypes.any };
static defaultProps = { reactivate: false }
render() {
return React.createElement('react-native-qrcode-scanner', this.props, this.props.children);
}
}
});
let wrapper = null;
const map = {};
const mockedParams = {
navigation: {
addListener: jest.fn((events, cb) => {
map[events] = cb
})
},
};
beforeEach(() => {
wrapper = render(
<ScanQRCodeScreen {...mockedParams}/>
);
})
describe('<Renderable>', () => {
test('ScanQRCodeScreen snapshot', async() => {
await act(async() => map.focus());
expect(wrapper).toMatchSnapshot();
})
})