将值传递给 Redux Saga 中的“next”函数

Passing values into the `next` function in Redux Saga

我有一个传奇:

export function* loadData() {
  const requestURL = 'http://www.web.address/thing';
  try {
    const data = yield call(getRequest, requestURL);
    yield put(dataLoaded(data));
  } catch (err) {
    yield put(dataError(err));
  }
}

我正在尝试这样测试它:

describe('loadData saga', () => {
  describe('200 response', () => {
    const getReq = jest.fn();
    const requestURL = 'mock.url.com';
    const generator = cloneableGenerator(loadData)();

    it('sends the request to the correct url', () => {
      expect(generator.next(getReq, requestURL).value).toEqual(call(getReq, requestURL));
    });
});

这个测试失败了,因为生成器似乎没有注意到我传递给下一个函数的内容,我不知道为什么。也就是说,测试接收 http://www.web.address/thing 作为 url 和 getRequest 函数,而不是我试图在 .next() 函数中传递的内容。

这也没有用:

generator.next(getReq(requestURL))

我误会了什么?

你实际上不应该在这里将任何参数传递给 next(),因为你的 saga 没有以前的产量并且不会将任何动态数据从以前的产量传递到 call - 它拥有一切它需要已经在范围内

因此在您的测试中,您将使用非模拟值检查 next().value 是否符合预期

import {getRequest} from 'same/place/as/saga/loads/getRequest';
const requestURL = 'http://www.web.address/thing';

expect(generator.next().value).toEqual(call(getRequest, requestURL));

你遇到的问题是你试图模拟并传入存根,在这种情况下,saga 无法注入它们

请记住,yield 将在下一次迭代之前停止生成器的执行,因此您实际上并不是 运行 此处的请求,只是停止并接收返回如何调用指令的对象getRequest 传递什么参数。

在上述测试后使用 .next(someData) 将允许您传入模拟数据作为请求响应的模拟

const mockData = {};
expect(generator.next(mockData).value).toEqual(put(dataLoaded(mockData)))

将 next() 的 args 视为允许模拟前一个 yield

的 return 值