我一直在玩rxjs和最近幾天可觀測的,並一直在努力尋找一種方法來測試Observable.ajax。我有以下的史詩,營造出請求https://jsonplaceholder.typicode.com/,我該如何測試Observable.ajax(redux-observable)?
export function testApiEpic (action$) {
return action$.ofType(REQUEST)
.switchMap(action =>
Observable.ajax({ url, method })
.map(data => successTestApi(data.response))
.catch(error => failureTestApi(error))
.takeUntil(action$.ofType(CLEAR))
)
}
其中,
export const REQUEST = 'my-app/testApi/REQUEST'
export const SUCCESS = 'my-app/testApi/SUCCESS'
export const FAILURE = 'my-app/testApi/FAILURE'
export const CLEAR = 'my-app/testApi/CLEAR'
export function requestTestApi() {
return { type: REQUEST }
}
export function successTestApi (response) {
return { type: SUCCESS, response }
}
export function failureTestApi (error) {
return { type: FAILURE, error }
}
export function clearTestApi() {
return { type: CLEAR }
}
時在瀏覽器中運行,但玩笑測試時沒有代碼工作正常。
我有嘗試,
1)創建基於https://redux-observable.js.org/docs/recipes/WritingTests.html測試。 store.getActions()只返回{type:REQUEST}。
const epicMiddleware = createEpicMiddleware(testApiEpic)
const mockStore = configureMockStore([epicMiddleware])
describe.only('fetchUserEpic',() => {
let store
beforeEach(() => {
store = mockStore()
})
afterEach(() => {
epicMiddleware.replaceEpic(testApiEpic)
})
it('returns a response,() => {
store.dispatch({ type: REQUEST })
expect(store.getActions()).toEqual([
{ type: REQUEST },
{ type: SUCCESS, response }
])
})
})
2)根據Redux-observable: failed jest test for epic創建測試。它返回
超時 - 在jasmine.DEFAULT_TIMEOUT_INTERVAL指定的超時時間內未調用異步回調。
it('returns a response', (done) => {
const action$ = ActionsObservable.of({ type: REQUEST })
const store = { getState:() => {} }
testApiEpic(action$, store)
.toArray()
.subscribe(actions => {
expect(actions).to.deep.equal([
{ type: SUCCESS, response }
])
done()
})
})
有人能指出我什麼是測試Observable.ajax正確的方法是什麼?