我正在测试一个本机组件,在该组件中导入一个依赖项(名为import和async),该依赖项执行一些逻辑并只返回一个布尔值,但我认为开玩笑不是在等待它完成。这也会记录错误。
“测试运行一秒钟后,玩笑并没有退出。
这通常意味着您的测试中没有停止异步操作。考虑使用--detectOpenHandles
运行Jest来解决此问题。”
目前,这是我尝试过的实现。
这是测试代码
// OfflineNotice.test.js
import React from 'react';
import { OfflineNotice } from './OfflineNotice';
jest.mock('../../service/user', () => ({
__esModule: true,
checkIfConnectivityIsValid: () => (
Promise.resolve(true)
),
}));
describe('<OfflineNotice/> test suite', () => {
const mockOnNetworkConnected = jest.fn();
test('it should render <OfflineNotice/> component', () => {
const wrapper = shallow(
<OfflineNotice
onNetworkConnected={mockOnNetworkConnected}
network={{
isConnected: true,
connectionType: 'value',
}}
/>,
);
expect(wrapper).toBeDefined();
});
});
我正在测试的组件的代码
// the dependency i need to mock
import { checkIfConnectivityIsValid } from '../../service/user';
// the implementation is as follows
export class OfflineNotice extends PureComponent {
componentWillMount() {
const { network } = this.props;
const { isConnected, connectionType } = network;
this.handleConnectivityChange(isConnected, connectionType);
}
componentDidUpdate() {
const { network } = this.props;
const { isConnected, connectionType } = network;
this.handleConnectivityChange(isConnected, connectionType);
}
handleConnectivityChange = async (isConnected, connectionType) => {
const { onNetworkConnected } = this.props;
// how the service was used only returns boolean
const isValid = await checkIfConnectivityIsValid(connectionType);
let status = null;
let message = null;
if (isConnected && isValid) {
status = 'online';
message = string.NETWORK_MESSAGE.AVAILABLE;
this.fadeOut();
onNetworkConnected();
} else if (isConnected) {
status = 'invalid';
message = string.NETWORK_MESSAGE.INVALID;
this.containerOpacity.setValue(1);
} else {
status = 'offline';
message = string.NETWORK_MESSAGE.NO_INTERNET;
this.containerOpacity.setValue(1);
}
this.setState({ status, message });
};
然后运行测试便可以渲染组件。尽管在代码覆盖率上,代码在“ const isValid = await checkIfConnectivityIsValid(connectionType);”上停止说不包括以后的声明的部分。