我目前正在开发一个反应原生应用程序,并尝试将redux-observable用于带有 redux 的中间件。
为简单起见,我只包括包含承诺的史诗,而不是用网络代码稀释它。
这是我针对只接受用户名、密码并应返回用户名、密码和身份验证令牌的身份验证 API 的单元测试。同样,这应该立即返回并让商店包含AUTHENTICATE
和AUTHENTICATE_FULFILLED
import configureMockStore from 'redux-mock-store';
import { createEpicMiddleware } from 'redux-observable';
import * as servicesRoot from '../app/services/root'
const epicMiddleware = createEpicMiddleware(servicesRoot.epics);
const mockStore = configureMockStore([epicMiddleware]);
describe('Session Service', () => {
let store;
beforeEach(() => {
store = mockStore();
});
afterEach(() => {
epicMiddleware.replaceEpic(servicesRoot.epics)
});
describe('Authentication API', () => {
it('I should receive an authToken', () => {
let username = 'myUsername'
let password = 'myPassword'
const data = { username, password, authToken: 'test_auth_token' };
let action = servicesRoot.actions.authenticate(username, password)
store.dispatch(action)
expect(store.getActions()).toEqual([
servicesRoot.actions.authenticate(username, password),
servicesRoot.actions.authenticate_fulfilled(data)
]);
})
})
})
我的身份验证史诗看起来像
import Rx from 'rxjs'
import * as actionTypes from './actionTypes'
import { authenticate_fulfilled } from './actions'
export const authenticateEpic = action$ =>
action$.ofType(actionTypes.AUTHENTICATE)
.mergeMap(action =>
Rx.Observable.fromPromise(Promise.resolve('test'))
.map(result => authenticate_fulfilled({ ...action.payload, authToken: 'test_auth_token'}))
)
注意:myservicesRoot.actions.authenticate
返回包含该AUTHENTICATE
类型的要使用的操作,并authenticate_fulfilled
返回另一个AUTHENTICATE_FULFILLED
操作。
我的单元测试输出是
FAIL __tests__/api.js
● Session Service › Authentication API › I should receive an authToken
expect(received).toEqual(expected)
Expected value to equal:
[{"payload": {"password": "myPassword", "username": "myUsername"}, "type": "AUTHENTICATE"}, {"payload": {"authToken": "test_auth_token", "password": "myPassword", "username": "myUsername"}, "type": "AUTHENTICATE_FULFILLED"}]
Received:
[{"payload": {"password": "myPassword", "username": "myUsername"}, "type": "AUTHENTICATE"}]
Difference:
- Expected
+ Received
@@ -4,14 +4,6 @@
"password": "myPassword",
"username": "myUsername",
},
"type": "AUTHENTICATE",
},
- Object {
- "payload": Object {
- "authToken": "test_auth_token",
- "password": "myPassword",
- "username": "myUsername",
- },
- "type": "AUTHENTICATE_FULFILLED",
- },
]
at Object.<anonymous> (__tests__/api.js:36:28)
Session Service
Authentication API
✕ I should receive an authToken (44ms)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 1.15s
Ran all test suites matching /api/.
如果我将史诗更改为,我的测试通过
export const authenticateEpic = action$ =>
action$.ofType(actionTypes.AUTHENTICATE)
.mergeMap(action =>
Rx.Observable.of('test')
.map(result => authenticate_fulfilled({ ...action.payload, authToken: 'test_auth_token'}))
)
我不确定为什么fromPromise
没有给出我期望的行为。我把它缩小到一个与承诺有关的问题。本质上,这将是网络请求的结果,然后进行相应处理。
谢谢您的帮助。