我想测试这个 observable 但我什么也没得到:
const fetchUsersApi = (action$: any) => action$.pipe(
ofType(FETCH_USERS),
mergeMap(() => from(
API.graphql(graphqlOperation(queries.LIST_ALL_USERS)),
).pipe(
map((res: any) => fetchUsersSuccess(
// TODO - standardise this to 'items' so fetchApi can be used
pathOr(null, ['data', 'listAllUsers', 'users'], res),
)),
catchError((error: Error) => {
const processedError = processAppSyncErrorMessage(error);
console.log('Error', processedError);
return of(addError(processedError), fetchUsersError(processedError));
}),
)),
);
测试如下:
import { TestScheduler } from 'rxjs/testing';
import { API } from 'aws-amplify';
import { ActionsObservable } from 'redux-observable';
import { fetchUsersSuccess, fetchUsers } from '../actions';
import fetchUsersEpic from './fetchUsersApi';
jest.mock('aws-amplify');
const testScheduler = new TestScheduler(
(actual, expected) => expect(actual).toStrictEqual(expected),
);
describe('fetchUsersEpic', () => {
it('should fetch the users', () => {
const mockFetchedUsers = [
{ id: 'fakeUser1' },
];
(API.graphql as jest.Mock).mockImplementation(() => Promise.resolve({
data: { listAllUsers: { users: mockFetchedUsers } },
}));
testScheduler.run((helpers) => {
const {
hot,
cold,
expectObservable,
flush,
} = helpers;
const action$ = cold('-a', {
a: fetchUsers(),
});
const reduxObservableaAction = ActionsObservable.from(action$);
const actual = fetchUsersEpic(reduxObservableaAction);
const expectedMarbles = '-b';
const expectedValues = { b: fetchUsersSuccess(mockFetchedUsers) };
expectObservable(actual).toBe(expectedMarbles, expectedValues);
flush();
});
});
});
我得到的结果是:
● fetchUsersEpic › 应该获取用户
expect(received).toStrictEqual(expected) // 深度相等
- 预计 - 18
- 收到 + 1
显然我在这里遗漏了一些东西,我认为返回的值应该是带有一些数据的 fetchUsersSuccess() 回调,但我们得到的是一个空数组。能得到一些想法会很棒。