跳至主要内容

测试 Saga

有两种主要方法可以测试 Saga:逐步测试 saga 生成器函数或运行完整的 saga 并断言副作用。

测试 Saga 生成器函数

假设我们有以下操作

const CHOOSE_COLOR = 'CHOOSE_COLOR'
const CHANGE_UI = 'CHANGE_UI'

const chooseColor = color => ({
type: CHOOSE_COLOR,
payload: {
color,
},
})

const changeUI = color => ({
type: CHANGE_UI,
payload: {
color,
},
})

我们想要测试 saga

function* changeColorSaga() {
const action = yield take(CHOOSE_COLOR)
yield put(changeUI(action.payload.color))
}

由于 Saga 总是产生一个 Effect,而这些 effect 具有基本的工厂函数(例如 put、take 等),因此测试可以检查产生的 effect 并将其与预期 effect 进行比较。要从 saga 中获取第一个产生的值,请调用其 next().value

const gen = changeColorSaga()

assert.deepEqual(gen.next().value, take(CHOOSE_COLOR), 'it should wait for a user to choose a color')

然后必须返回一个值以分配给 action 常量,该常量用作 put effect 的参数

const color = 'red'
assert.deepEqual(
gen.next(chooseColor(color)).value,
put(changeUI(color)),
'it should dispatch an action to change the ui',
)

由于没有更多 yield,因此下次调用 next() 时,生成器将完成

assert.deepEqual(gen.next().done, true, 'it should be done')

分支 Saga

有时你的 saga 会有不同的结果。为了测试不同的分支而不重复导致它的所有步骤,你可以使用实用函数 cloneableGenerator

这次我们添加了两个新的操作,CHOOSE_NUMBERDO_STUFF,以及相关的操作创建者

const CHOOSE_NUMBER = 'CHOOSE_NUMBER'
const DO_STUFF = 'DO_STUFF'

const chooseNumber = number => ({
type: CHOOSE_NUMBER,
payload: {
number,
},
})

const doStuff = () => ({
type: DO_STUFF,
})

现在,正在测试的 saga 将在等待 CHOOSE_NUMBER 操作之前放置两个 DO_STUFF 操作,然后根据数字是偶数还是奇数放置 changeUI('red')changeUI('blue')

function* doStuffThenChangeColor() {
yield put(doStuff())
yield put(doStuff())
const action = yield take(CHOOSE_NUMBER)
if (action.payload.number % 2 === 0) {
yield put(changeUI('red'))
} else {
yield put(changeUI('blue'))
}
}

测试如下

import { put, take } from 'redux-saga/effects'
import { cloneableGenerator } from '@redux-saga/testing-utils'

test('doStuffThenChangeColor', assert => {
const gen = cloneableGenerator(doStuffThenChangeColor)()
gen.next() // DO_STUFF
gen.next() // DO_STUFF
gen.next() // CHOOSE_NUMBER

assert.test('user choose an even number', a => {
// cloning the generator before sending data
const clone = gen.clone()
a.deepEqual(clone.next(chooseNumber(2)).value, put(changeUI('red')), 'should change the color to red')

a.equal(clone.next().done, true, 'it should be done')

a.end()
})

assert.test('user choose an odd number', a => {
const clone = gen.clone()
a.deepEqual(clone.next(chooseNumber(3)).value, put(changeUI('blue')), 'should change the color to blue')

a.equal(clone.next().done, true, 'it should be done')

a.end()
})
})

另请参阅:任务取消 以测试 fork effect

测试完整的 Saga

虽然测试 saga 的每个步骤可能很有用,但在实践中,这会导致测试变得脆弱。相反,最好运行整个 saga 并断言预期的 effect 已经发生。

假设我们有一个调用 HTTP API 的基本 saga

function* callApi(url) {
const someValue = yield select(somethingFromState)
try {
const result = yield call(myApi, url, someValue)
yield put(success(result.json()))
return result.status
} catch (e) {
yield put(error(e))
return -1
}
}

我们可以使用模拟值运行 saga

const dispatched = []

const saga = runSaga(
{
dispatch: action => dispatched.push(action),
getState: () => ({ value: 'test' }),
},
callApi,
'http://url',
)

然后可以编写一个测试来断言分派的 action 和模拟调用

import sinon from 'sinon'
import * as api from './api'

test('callApi', async assert => {
const dispatched = []
sinon.stub(api, 'myApi').callsFake(() => ({
json: () => ({
some: 'value',
}),
}))
const url = 'http://url'
const result = await runSaga(
{
dispatch: action => dispatched.push(action),
getState: () => ({ state: 'test' }),
},
callApi,
url,
).toPromise()

assert.true(myApi.calledWith(url, somethingFromState({ state: 'test' })))
assert.deepEqual(dispatched, [success({ some: 'value' })])
})

另请参阅:存储库示例

https://github.com/redux-saga/redux-saga/blob/main/examples/counter/test/sagas.js

https://github.com/redux-saga/redux-saga/blob/main/examples/shopping-cart/test/sagas.js

测试库

虽然以上两种测试方法都可以用原生方式编写,但存在一些库可以使这两种方法更容易。此外,一些库可以用来以第三种方式测试 saga:记录特定的副作用(但不是全部)。

Sam Hogarth (@sh1989) 的文章很好地总结了不同的选项。

对于逐个步骤测试每个生成器 yield,有 redux-saga-testredux-saga-testingredux-saga-test-engine 用于记录和测试特定的副作用。对于集成测试,redux-saga-tester。而 redux-saga-test-plan 实际上可以涵盖所有三个方面。

redux-saga-testredux-saga-testing 用于逐步测试

redux-saga-test 库为您的逐步测试提供了语法糖。fromGenerator 函数返回一个值,该值可以使用 .next() 手动迭代,并使用相关的 saga 效果方法进行断言。

import fromGenerator from 'redux-saga-test'

test('with redux-saga-test', () => {
const generator = callApi('url')
/*
* The assertions passed to fromGenerator
* requires a `deepEqual` method
*/
const expect = fromGenerator(assertions, generator)

expect.next().select(somethingFromState)
expect.next(selectedData).call(myApi, 'url', selectedData)
expect.next(result).put(success(result.json))
})

redux-saga-testing 库提供了一个方法 sagaHelper,它接受您的生成器并返回一个值,该值的工作方式非常类似于 Jest 的 it() 函数,但也会推进正在测试的生成器。传递给回调的 result 参数是生成器产生的值。

import sagaHelper from 'redux-saga-testing'

test('with redux-saga-testing', () => {
const it = sagaHelper(callApi())

it('should select from state', selectResult => {
// with Jest's `expect`
expect(selectResult).toBe(value)
})

it('should select from state', apiResponse => {
// without tape's `test`
assert.deepEqual(apiResponse.json(), jsonResponse)
})

// an empty call to `it` can be used to skip an effect
it('', () => {})
})

redux-saga-test-plan

这是最通用的库。testSaga API 用于精确顺序测试,而 expectSaga 用于记录副作用和集成测试。

import { expectSaga, testSaga } from 'redux-saga-test-plan';

test('exact order with redux-saga-test-plan', () => {
return testSaga(callApi, 'url')
.next()
.select(selectFromState)
.next()
.call(myApi, 'url', valueFromSelect);

...
});

test('recorded effects with redux-saga-test-plan', () => {
/*
* With expectSaga, you can assert that any yield from
* your saga occurs as expected, *regardless of order*.
* You must call .run() at the end.
*/
return expectSaga(callApi, 'url')
.put(success(value)) // last effect from our saga, first one tested

.call(myApi, 'url', value)
.run();
/* notice no assertion for the select call */
});

test('test only final effect with .provide()', () => {
/*
* With the .provide() method from expectSaga
* you can by pass in all expected values
* and test only your saga's final effect.
*/
return expectSaga(callApi, 'url')
.provide([
[select(selectFromState), selectedValue],
[call(myApi, 'url', selectedValue), response]
])
.put(success(response))
.run();
});

test('integration test with withReducer', () => {
/*
* Using `withReducer` allows you to test
* the state shape upon completion of your reducer -
* a true integration test for your Redux store management.
*/

return expectSaga(callApi, 'url')
.withReducer(myReducer)
.provide([
[call(myApi, 'url', value), response]
])
.hasFinalState({
data: response
})
.run();
});

redux-saga-test-engine

这个库在设置方面与 redux-saga-test-plan 非常相似,但最适合用于记录效果。提供一组 saga 通用效果,由 createSagaTestEngine 函数监视,该函数反过来返回一个函数。然后提供您的 saga 和特定效果及其参数。

const collectedEffects  = createSagaTestEngine(['SELECT', 'CALL', 'PUT']);
const actualEffects = collectEffects(mySaga, [ [myEffect(arg), value], ... ], argsToMySaga);

actualEffects 的值是一个数组,包含与所有收集效果产生的值相等的元素,按发生顺序排列。

import createSagaTestEngine from 'redux-saga-test-engine'

test('testing with redux-saga-test-engine', () => {
const collectEffects = createSagaTestEngine(['CALL', 'PUT'])

const actualEffects = collectEffects(
callApi,
[[select(selectFromState), selectedValue], [call(myApi, 'url', selectedValue), response]],
// Any further args are passed to the saga
// Here it is our URL, but typically would be the dispatched action
'url',
)

// assert that the effects you care about occurred as expected, in order
assert.equal(actualEffects[0], call(myApi, 'url', selectedValue))
assert.equal(actualEffects[1], put(success, response))

// assert that your saga does nothing unexpected
assert.true(actualEffects.length === 2)
})

redux-saga-tester

另一个用于集成测试的库。这个库提供了一个 sagaTester 类,您可以使用商店的初始状态和 reducer 实例化它。

要测试您的 saga,sagaTester 实例使用您的 saga 及其参数调用 start() 方法。这将运行您的 saga 直到结束。然后,您可以断言效果已发生、操作已分派以及状态已按预期更新。

import SagaTester from 'redux-saga-tester';

test('with redux-saga-tester', () => {
const sagaTester = new SagaTester({
initialState: defaultState,
reducers: reducer
});

sagaTester.start(callApi);

sagaTester.dispatch(actionToTriggerSaga());

await sagaTester.waitFor(success);

assert.true(sagaTester.wasCalled(success(response)));

assert.deepEqual(sagaTester.getState(), { data: response });
});

effectMiddlewares

提供了一种原生方式来执行集成测试,而无需上述库之一。

想法是,您可以在测试文件中创建一个带有 saga 中间件的真实 redux 商店。saga 中间件接受一个对象作为参数。该对象将具有一个 effectMiddlewares 值:一个函数,您可以在其中拦截/劫持任何效果并自行解析它 - 以非常 redux 的方式将其传递给下一个中间件。

在您的测试中,您将启动一个 saga,使用 effectMiddlewares 拦截/解析异步效果,并断言诸如状态更新之类的内容,以测试您的 saga 和商店之间的集成。

以下来自 文档 的示例

test('effectMiddleware', assert => {
assert.plan(1)

let actual = []

function rootReducer(state = {}, action) {
return action
}

const effectMiddleware = next => effect => {
if (effect === apiCall) {
Promise.resolve().then(() => next('injected value'))
return
}
return next(effect)
}

const middleware = sagaMiddleware({ effectMiddlewares: [effectMiddleware] })
const store = createStore(rootReducer, {}, applyMiddleware(middleware))

const apiCall = call(() => new Promise(() => {}))

function* root() {
actual.push(yield all([call(fnA), apiCall]))
}

function* fnA() {
const result = []
result.push((yield take('ACTION-1')).val)
result.push((yield take('ACTION-2')).val)
return result
}

const task = middleware.run(root)

Promise.resolve()
.then(() => store.dispatch({ type: 'ACTION-1', val: 1 }))
.then(() => store.dispatch({ type: 'ACTION-2', val: 2 }))

const expected = [[[1, 2], 'injected value']]

task
.toPromise()
.then(() => {
assert.deepEqual(
actual,
expected,
'effectMiddleware must be able to intercept and resolve effect in a custom way',
)
})
.catch(err => assert.fail(err))
})