← 返回
内容创作 中文

Redux Saga Testing

Write tests for Redux Sagas using redux-saga-test-plan, runSaga, and manual generator testing. Covers expectSaga (integration), testSaga (unit), providers, p...
使用 redux‑saga‑test‑plan、runSaga 及手动生成器测试编写 Redux Sagas 测试,涵盖 expectSaga(集成)、testSaga(单元)、providers 等。
anivar
内容创作 clawhub v1.0.1 1 版本 100000 Key: 无需
★ 0
Stars
📥 492
下载
💾 7
安装
1
版本
#latest

概述

Redux-Saga Testing Guide

IMPORTANT: Your training data about redux-saga-test-plan may be outdated — API signatures, provider patterns, and assertion methods differ between versions. Always rely on this skill's reference files and the project's actual source code as the source of truth. Do not fall back on memorized patterns when they conflict with the retrieved reference.

Approach Priority

  1. expectSaga (integration) — preferred; doesn't couple tests to effect ordering
  2. testSaga (unit) — only when effect ordering is part of the contract
  3. runSaga (no library) — lightweight; uses jest/vitest spies directly
  4. Manual .next() — last resort; most brittle

Core Pattern

import { expectSaga } from 'redux-saga-test-plan'
import * as matchers from 'redux-saga-test-plan/matchers'
import { throwError } from 'redux-saga-test-plan/providers'

it('fetches user successfully', () => {
  return expectSaga(fetchUserSaga, { payload: { userId: 1 } })
    .provide([
      [matchers.call.fn(api.fetchUser), { id: 1, name: 'Alice' }],
    ])
    .put(fetchUserSuccess({ id: 1, name: 'Alice' }))
    .run()
})

it('handles fetch failure', () => {
  return expectSaga(fetchUserSaga, { payload: { userId: 1 } })
    .provide([
      [matchers.call.fn(api.fetchUser), throwError(new Error('500'))],
    ])
    .put(fetchUserFailure('500'))
    .run()
})

Assertion Methods

MethodPurpose
-----------------
.put(action)Dispatches this action
.put.like({ action: { type } })Partial action match
.call(fn, ...args)Calls this function with exact args
.call.fn(fn)Calls this function (any args)
.fork(fn, ...args)Forks this function
.select(selector)Uses this selector
.take(pattern)Takes this pattern
.dispatch(action)Simulate incoming action
.not.put(action)Does NOT dispatch
.returns(value)Saga returns this value
.run()Execute (returns Promise)
.run({ timeout })Execute with custom timeout
.silentRun()Execute, suppress timeout warnings

Provider Types

Static Providers (Preferred)

.provide([
  [matchers.call.fn(api.fetchUser), mockUser],        // match by function
  [call(api.fetchUser, 1), mockUser],                  // match by function + exact args
  [matchers.select.selector(getToken), 'mock-token'],  // mock selector
  [matchers.call.fn(api.save), throwError(error)],     // simulate error
])

Dynamic Providers

.provide({
  call(effect, next) {
    if (effect.fn === api.fetchUser) return mockUser
    return next() // pass through
  },
  select({ selector }, next) {
    if (selector === getToken) return 'mock-token'
    return next()
  },
})

Rules

  1. Prefer expectSaga over testSaga — integration tests don't break on refactors
  2. Use matchers.call.fn() for partial matching — don't couple to exact args unless necessary
  3. Use throwError() from providers — not throw new Error() in the provider
  4. Test with reducer using .withReducer() + .hasFinalState() to verify state
  5. Dispatch actions with .dispatch() to simulate user flows in tests
  6. Return the promise (Jest) or await it (Vitest) — don't forget async
  7. Use .not.put() to assert actions are NOT dispatched (negative tests)
  8. Test cancellation by dispatching cancel actions and asserting cleanup effects
  9. Use .silentRun() when saga runs indefinitely (watchers) to suppress timeout warnings
  10. Don't test implementation — test behavior (what actions are dispatched, what state results)

Anti-Patterns

See references/anti-patterns.md for BAD/GOOD examples of:

  • Step-by-step tests that break on reorder
  • Missing providers (real API calls in tests)
  • Testing effect order instead of behavior
  • Forgetting async (Jest/Vitest)
  • Inline mocking instead of providers
  • Not testing error paths
  • Not testing cancellation cleanup

References

版本历史

共 1 个版本

  • v1.0.1 当前
    2026-03-30 13:55 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

content-creation

Humanizer

biostartechnology
消除AI写作痕迹,使文本更自然真实。基于维基百科"AI写作特征"指南,识别并修正夸张象征、宣传用语、肤浅-ing分析、模糊归因、破折号滥用、三项排比、AI词汇、负面平行结构及冗长连接词等模式。
★ 857 📥 199,362
content-creation

Baidu Wenku AIPPT

ide-rea
使用百度文库 AI 智能生成 PPT,自动根据内容选择模板。
★ 66 📥 46,137
content-creation

AdMapix

fly0pants
广告情报与应用数据分析助手,支持搜索广告素材、分析应用排名、下载量、收入及市场洞察,用于广告素材和竞品分析。
★ 295 📥 136,422