【问题标题】:RxJS / Redux-observables: How would I test EventEmitter?RxJS / Redux-observables:我将如何测试 EventEmitter?
【发布时间】:2019-06-11 15:31:45
【问题描述】:

我正在尝试测试当我的上传对象上的完成事件被触发时,redux 操作被触发。

这是我的史诗:

const uploadFileEpic = (action$, state$, dependencies$) =>
  action$.pipe(
    ofType(uploadActions.UPLOAD_FILE),
    mergeMap(({ payload }) => {
      const { file, masterHandle } = payload;

      return new Observable(o => {
        const upload = masterHandle.uploadFile("/", file);
        const handle = upload.handle;

        upload.on("finish", () => {
          o.next(
            uploadActions.uploadSuccess({
              masterHandle
            })
          );
          o.complete();
        });
      });
    })
  );

这是我到目前为止所写的。它不起作用:

import { of } from "rxjs";
import "rxjs/add/operator/toArray";
import { EventEmitter } from "events";

import uploadActions from "../actions/upload-actions";
import uploadEpic from "./upload-epic";

test("uploadFilesEpic filesActions.UPLOAD_FILE on success", done => {
  const file = { name: "f1" };
  const upload = new EventEmitter();
  upload.handle = "h1";

  const masterHandle = {
    uploadFile: jest.fn(() => upload)
  };

  const action$ = of(uploadActions.uploadFile({ file, masterHandle }));

  upload.emit("finish");

  uploadEpic(action$).subscribe(actions => {
    expect(actions).toEqual(uploadActions.uploadSuccess({ masterHandle }));
    done();
  });
});

它说异步回调没有被触发:

 FAIL  src/redux/epics/upload-epic.test.js (8.531s)
  ✓ uploadFilesEpic filesActions.UPLOAD_FILES (9ms)
  ✕ uploadFilesEpic filesActions.UPLOAD_FILE on success (5021ms)

  ● uploadFilesEpic filesActions.UPLOAD_FILE on success

    Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error:

      23 | });
      24 |
    > 25 | test("uploadFilesEpic filesActions.UPLOAD_FILE on success", done => {
         | ^
      26 |   const file = { name: "f1" };
      27 |   const upload = new EventEmitter();
      28 |   upload.handle = "h1";

      at new Spec (node_modules/jest-config/node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
      at Object.test (src/redux/epics/upload-epic.test.js:25:1)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        9.297s

测试失败对我来说是有道理的,但我不确定如何订阅史诗、触发 finish 事件,然后检查史诗返回的操作。

【问题讨论】:

  • 尝试将upload.emit("finish")移动到测试的底部。
  • @Reactgular 哇!

标签: rxjs redux-observable


【解决方案1】:

完成上传的事件在测试中过早发出。 EventEmitter 不保留事件的缓冲区,如果没有人订阅,则偶数丢失。

将发射 "finish" 移动到测试的底部。

upload.emit("finish"); // must emit after subscribing

【讨论】:

    猜你喜欢
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多