gpt4 book ai didi

unit-testing - 如何在 React-Native 中 Jest 模拟 Picker 和 Picker.Item?

转载 作者:行者123 更新时间:2023-12-01 09:49:48 25 4
gpt4 key购买 nike

我正在尝试对这段代码进行快照测试:

import React, { Component } from 'react';
import {
Picker,
} from 'react-native';

export default class TestComponent extends Component {

render() {
return (
<Picker
selectedValue={this.props.asset.type}
onValueChange={this.props.onTypeChange}>
<Picker.Item label="Type of asset" value="default" />
<Picker.Item label="Car" value="car" />
<Picker.Item label="Boat" value="boat" />
<Picker.Item label="Ship" value="ship" />
</Picker>
);
}
}

我的测试现在看起来像这样:

import 'react-native';
import React from 'react';
import TestComponent from './TestComponent';

import renderer from 'react-test-renderer';

describe('TestComponent', () => {
const asset = {
type: 'car',
}
it('renders correctly', () => {
const tree = renderer.create(
<TestComponent
asset={asset} />
).toJSON();
expect(tree).toMatchSnapshot();
});
})

我的问题是:

TypeError: Cannot read property '_tag' of undefined

我认为我应该根据 this issue 模拟它

我尝试过简单地添加:

jest.mock('Picker', () => 'Picker')

但它仍然会引发错误,因为 Picker.Item 仍然没有被模拟

Invariant Violation: Element type is invalid: expected a string (for built-
in components) or a class/function (for composite components)
but got: undefined. Check the render method of `TestComponent`.

我尝试过的其他变体无济于事:

jest.mock('Picker', () => {return {Item: 'Item'}});
----------------------------------------------------
class Picker{
Item = 'PickerItem'
}
jest.mock('Picker', () => {
return Picker;
});

最佳答案

创建了 github issue同样,这是一个有效的答案:

jest.mock('Picker', () => {
const Picker = class extends Component {
static Item = props => React.createElement('Item', props, props.children);
static propTypes = { children: React.PropTypes.any };

render() {
return React.createElement('Picker', this.props, this.props.children);
}
}
return Picker;
})

关于unit-testing - 如何在 React-Native 中 Jest 模拟 Picker 和 Picker.Item?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40136317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com