首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >redux-saga测试while( true ) -使saga.next().done为true

redux-saga测试while( true ) -使saga.next().done为true
EN

Stack Overflow用户
提问于 2020-12-10 23:18:34
回答 1查看 125关注 0票数 1

我正在测试一个民调传奇。

代码语言:javascript
复制
export function* sagaWithPolling() {
  while (true) {
    try {
      // saga body
    } catch (error) {
      yield put(stopPolling());
      yield put(displayError(error));
    }
  }
}

测试:

代码语言:javascript
复制
 describe('error flow', () => {
    const saga = sagaWithPolling();

    saga.next();

    test('stop polling', () => {
      const actual = saga.throw(TEST_ERROR).value;
      const expected = put(stopPolling());

      expect(actual).toEqual(expected);
    });

    test('should display error', () => {
      const actual = saga.next().value;
      const expected = put(displayError(TEST_ERROR));

      expect(actual).toEqual(expected);
    });

    test('be done', () => {
      const actual = saga.next().done;
      const expected = true;

      expect(actual).toEqual(expected);
    });
  });

这个测试对于一般的传奇来说是通过的,但是对于轮询和使用while(true)的测试,它在最后一步失败了,因为saga.next().done是false,因为它继续轮询。你知道如何指出它停止了轮询吗?

EN

回答 1

Stack Overflow用户

发布于 2021-06-22 15:16:52

由于在生成器中定义了无限循环,gen.next()将让生成器在该无限循环(try块)中无限取值。该值始终为{value: 1, done: false}。生成器将永远不会结束。

您应该使用Generator.prototype.return()返回给定值并完成生成器。

例如。

saga.ts

代码语言:javascript
复制
import { put } from 'redux-saga/effects';

export function stopPolling() {
  return { type: 'STOP_POLLING' };
}
export function displayError(error) {
  return { type: 'DISPLAY_ERROR', payload: error };
}

export function* sagaWithPolling() {
  while (true) {
    try {
      // saga body
      yield 1;
    } catch (error) {
      yield put(stopPolling());
      yield put(displayError(error));
    }
  }
}

saga.test.ts

代码语言:javascript
复制
import { put } from 'redux-saga/effects';
import { displayError, sagaWithPolling, stopPolling } from '.';

describe('error flow', () => {
  const saga = sagaWithPolling();
  const TEST_ERROR = new Error('network');

  saga.next();

  test('stop polling', () => {
    const actual = saga.throw(TEST_ERROR).value;
    const expected = put(stopPolling());
    expect(actual).toEqual(expected);
  });

  test('should display error', () => {
    const actual = saga.next().value;
    const expected = put(displayError(TEST_ERROR));
    expect(actual).toEqual(expected);
  });

  test('be done', () => {
    const actual = saga.return().done;
    const expected = true;
    expect(actual).toEqual(expected);
  });
});

测试结果:

代码语言:javascript
复制
 PASS  src/stackoverflow/65237271/index.test.ts
  error flow
    ✓ stop polling (3 ms)
    ✓ should display error (1 ms)
    ✓ be done

Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        2.067 s, estimated 3 s
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65237271

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档