Jest test mock -- 在另一个函数中模拟获取



我有一个有状态的组件,我正在尝试测试。此组件用作调用我的其他函数之前的中间步骤。有点像这样工作

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);
});
})

但这似乎不起作用

编辑2:

我现在正在调查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');

它返回一个对象而不是某种形式的字符串。 jest 足够好,可以打印出对象中的内容,而且没有什么我期望的,这很["abc", "def"]

您可以使用 nock 或 fetch-mock 等库模拟 HTTP 请求的响应。

最新更新