【发布时间】:2020-03-09 16:08:08
【问题描述】:
我正在编写一个简单的应用程序,在单击按钮后,应该执行对 spotify API 的异步调用,并且当 promise 解决时它应该更新组件的状态。我正在使用反应钩子来管理我的组件中的状态。
在我的测试中,我模拟了 API 调用。
spotify.jsx
export default class Spotify {
constructor(token) {
this.axiosInstance = axios.create({
baseURL: baseURL,
headers: buildHeaders(token),
});
}
async getUserInfo() {
const userInfo = await this.axiosInstance({
url: `/me`,
});
return userInfo.data
}
}
spotify 模拟:
const getUserInfoMock = jest.fn();
const mock = jest.fn().mockImplementation(() => ({
getUserInfo: getUserInfoMock,
}));
export default mock;
用户.jsx
const User = props => {
const [user, setUser] = useState(null);
const {token} = useContext(AuthContext);
const spotify = useMemo(() => new Spotify(token), [token]);
const getUserInfo = async () => {
console.log("button clicked")
const fetched = await spotify.getUserInfo();
console.log(fetched)
setUser(fetched);
}
return (
<React.Fragment>
<p>user page</p>
<button onClick={getUserInfo} > click me </button>
{user && (
<div>
<p>{user.display_name}</p>
<p>{user.email}</p>
</div>
)}
</React.Fragment>
);
};
我的问题是如何正确测试这种行为。我设法让它通过了,但不是在simulate() 上调用await 是一个丑陋的黑客吗?模拟不返回承诺。这是一个测试:
it('updates display info with data from api', async () => {
const userInfo = {
display_name: 'Bob',
email: 'bob@bob.bob',
};
spotifyMock.getUserInfo.mockImplementation(() => Promise.resolve(userInfo));
wrapper = mount(<User />);
expect(wrapper.find('p')).toHaveLength(1);
await wrapper
.find('button')
.last()
.simulate('click');
wrapper.update();
expect(wrapper.find('p')).toHaveLength(3);
});
另一方面,当我只检查是否调用了 mock 时,我不需要使用 async/await 和测试通过:
it('calls spotify api on click', () => {
wrapper = mount(<User />);
expect(spotifyMock.getUserInfo).not.toHaveBeenCalled();
wrapper
.find('button')
.last()
.simulate('click');
expect(spotifyMock.getUserInfo).toHaveBeenCalledTimes(1);
});
我想知道我的测试方式是否正确,如果我想添加一个功能以在组件呈现时从 api 获取数据 - 使用 useEffect 挂钩。 Enzyme 是否完全支持反应钩子?
即使我包装了mount 和simulate 函数,我也会遇到警告Warning: An update to User inside a test was not wrapped in act(...)。
【问题讨论】:
标签: javascript reactjs unit-testing asynchronous enzyme