本文介绍了如何测试我的 redux saga spawn 代码块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 jest 测试 spawn 块...我在 beforeEach 块中创建了一个生成器,我正在检查
generator.next() 函数,像这样

i want to test spawn block using jest...i created a generator in beforeEach block and i'm checking through
generator.next() function, like this

    beforeEach(() => {
        generator = saga.postCompare();
    });

我的代码是这样的

    export function* LoadData() {
      let someVariable;
      try {
       for (let index = 0; index < 3; index += 1) {
            yield spawn(loadUserData, varaiable1, variable2);
       }
     }
   }

   export function* loadUserData(Prop1, Prop2) {
      try {
        const userData = yield call(serverManager.fetch1,prop1, prop2 );
        const isUserSelected = yield* isUserSelected();
        if (!isUserSelected) {
          return;
        }
        yield put(
          Actions.onRequestSucceededForUser(userData.data.value, prop1),
        );
      }
    }

推荐答案

也许最直接的解决方案可以用于测试 redux-saga 生成器 - 只是根据它们的工作原理定义,而不是嘲笑任何东西.因此,每个 saga 只是生成器函数,它在每个 yield 操作符处产生到父函数的控制流.此外,saga-effects in fact 什么都不做——只是创建特殊的表单对象,这是 redux-saga 内部进程管理器(https://github.com/redux-saga/redux-saga/blob/master/src/internal/io.js )

Maybe most straightforward solution is accepted for testing redux-saga generators - just by definition how they works, and without mocking anything. So, every saga is just generator function, which yields control flow to parent function at every yield operator. Also, saga-effects in facts does nothing - just create special form object, which is acceptable by redux-saga internal process manager (https://github.com/redux-saga/redux-saga/blob/master/src/internal/io.js )

因此,您可以轻松地从测试运行器中运行被测试的 saga 函数,并对返回的操作执行断言,如下所示:

So, you can easily run under-test saga function from test runner, and perform assertions for returned actions, like this:

const saga = LoadData();
assert(saga.next()).to.be.deep.equal(spawn(loadUserData, varaiable1, variable2))
assert(saga.next()).to.be.deep.equal(spawn(loadUserData, varaiable1, variable2))
assert(saga.next()).to.be.deep.equal(spawn(loadUserData, varaiable1, variable2))

这样函数loadUserData不会被执行,也会创建效果描述符对象

In this way function loadUserData will not be executed, and also effects descriptor objects will be created

这篇关于如何测试我的 redux saga spawn 代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-04 16:20