我有一个要测试的有状态组件。该组件在调用我的其他功能之前作为中间步骤。 Kinda就是这样
class MyList extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
this.props.loadMystuff().then(() => {
if (this.state.eKey !== this.props.eKey) {
let eKey = this.props.eKey;
this.fetchSList(eKey);
}
}).catch((error) => toast(error.message));
}
fetchSList(eKey) {
if (eKey !== '') {
fetch(`some_api_url_config/${this.props.entityKey}`)
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
}
}
render() {
const { error, isLoaded, items } = this.state;
if (items) {
return (
<div>
<h3>S List</h3>
<ul>
{items.map(item => (
<li key={item}>
{item}
</li>
))}
</ul>
</div>
);
} else if (error) {
return <div>Error: List Missing...{error.message}</div>;
} else if (!isLoaded) {
return <div>Loading List...</div>;
} else {
return <div>Not Found</div>;
}
}
}
loadMystuff
本质上给了我一个eKey
,我可以用它来调用fetchSList
,后者可以调用fetch
我想模拟fetch
并使其返回字符串数组,但我没有运气实现这一目标。
我的测试脚本看起来像
describe(<MyList />, () => {
let wrapper;
let eKey = 'some_str';
it("should have some listed items", () => {
wrapper = shallow(<MyList loadMystuff={loadMystuff()}
eKey={eKey}/>
);
expect(wrapper.find("div").find("ul").find("li").length).toBeGreaterThan(0);
})
)
如何使fetch命令返回类似['abc', 'def', 'ghi']
的数组?
编辑:
阅读https://medium.com/@ferrannp/unit-testing-with-jest-redux-async-actions-fetch-9054ca28cdcd
后我想出了
it("should have some listed items", () => {
window.fetch = jest.fn().mockImplementation(() =>
Promise.resolve(mockResponse(200, null, '["abc", "def"]')));
return store.dispatch(MyList(loadMystuff=loadMystuff(), eKey=eKey))
.then(() => {
const expectedActions = store.getActions();
console.log('expectedActions', expectedActions);
});
})
但这似乎不起作用
EDIT2:
我正在调查fetch-mock
包裹。
我的功能仍然是fetchSList
,其中有一个fetch
。我的测试方式为
let eKey = 'some_key';
describe(<MyList />, () => {
fetchMock.get('*', '["abc", "def"]');
it("should have some listed items", () => {
wrapper = shallow(<MyList loadMyStuff={loadMyStuff()}
eKey={eKey}/>
);
expect(wrapper.find("div").find("ul").find("li")).toBe('something_something');
,它将返回一个对象而不是某种形式的字符串。开玩笑地很好,可以打印出对象中的内容,而且我什么也没想到,这是["abc", "def"]