我无法通过并发API调用测试功能。这是我要测试的依赖redux-thunk的代码:
public void getUsersFromServer() {
Flowable<List<User>> usersObservable = mainRepository.fetchUsersFromServer()
.filter(new Predicate<List<User>>() {
@Override
public boolean test(List<User> users) throws Exception {
return !users.isEmpty(); // put your filter condition
}
});
final LiveData<List<User>> source = LiveDataReactiveStreams.fromPublisher(usersObservable);
liveUsers.addSource(source, new Observer<List<User>>() {
@Override
public void onChanged(List<User> users) {
liveUsers.setValue(users);
liveUsers.removeSource(source);
}
});
}
它将并发请求发送到API,然后在成功时将操作调度到redux存储。这些请求是独立的,因此我并不在乎哪个优先执行。
但是,当我尝试使用moxios和redux-mock-store测试此代码时,我只能从模拟存储中的第一个请求中分派动作:
const loadResources = () => {
return (dispatch) => {
dispatch(setLoaderState(true))
// events
API.get('/internal/timeo/api/v0/actions')
.then(response => initialFetchEventsSuccess(dispatch, response))
.catch(error => onRequestErrorCallback(dispatch, error));
// clients
API.get('/internal/obeya/api/v0/clients')
.then(response => initialFetchClientsSuccess(dispatch, response))
.catch(error => onRequestErrorCallback(dispatch, error));
// resources
API.get('/internal/obeya/api/v0/resources')
.then(response => getRessourcesSuccess(dispatch, response))
.catch(error => onRequestErrorCallback(dispatch, error));
}
}
// on successfull fetch we dispatch data to the store
const initialFetchEventsSuccess = (dispatch, data) => {
dispatch(setLoaderState(false))
dispatch(setErrorState(false))
dispatch({
type: LOAD_EVENTS,
payload: data.data
});
}
// on successfull fetch we dispatch data to the store
const initialFetchClientsSuccess = (dispatch, data) => {
dispatch(setLoaderState(false))
dispatch(setErrorState(false))
dispatch({
type: LOAD_CLIENTS,
payload: data.data
})
}
// on successfull fetch we dispatch data to the store
const getRessourcesSuccess = (dispatch, data) => {
dispatch({
type: SET_RESOURCES,
payload: data.data
})
}
在这里,无论我设置了什么超时,最终我只会得到LOAD_EVENTS动作。我在做什么错了?
答案 0 :(得分:1)
可能迟到了,但我在寻找类似答案时在 moxios repo 中遇到了这个问题。
https://github.com/axios/moxios#mocking-a-axioscreate-instance
所以,您的方向是正确的。只需要断言 axios 实例并以这种方式获得结果。
let axiosInstance;
beforeEach(() => {
axiosInstance = axios.create();
moxios.install(axiosInstance);
});
afterEach(() => {
moxios.uninstall(axiosInstance);
});
test('Should get results', (done) => {
moxios.stubRequest(`url`, {status: 200, response: response /* or response */});
axiosInstance.get(`url`)
.then(res => res.status === 200)
.finally(done)
})