如何使用 RxJS 主题进行模拟和测试?

How to Mock and test using an RxJS subject?

我有一些函数接受我想要测试的 RxJS 主题(支持套接字)。我想以一种非常请求回复的方式来嘲笑这个主题。因为我不确定一个干净的 Rx 方法来做到这一点,我很想使用 EventEmitter 来形成我的假套接字。

一般来说,我想:

我确实需要能够使用消息中的数据来形成响应。


正在测试的代码是

export function acquireKernelInfo(sock) {
  // set up our JSON payload
  const message = createMessage('kernel_info_request');

  const obs = shell
    .childOf(message)
    .ofMessageType('kernel_info_reply')
    .first()
    .pluck('content', 'language_info')
    .map(setLanguageInfo)
    .publishReplay(1)
    .refCount();

  sock.next(message);
  return obs;
}

您可以手动创建两个主题并 "glue them together" 作为一个主题 Subject.create:

const sent = new Rx.Subject();
const received = new Rx.Subject();

const mockWebSocketSubject = Subject.create(sent, received)

const s1 = sent.subscribe(
  (msg) => sentMsgs.push({ next: msg }),
  (err) => sentMsgs.push({ error: err }),
  () => sendMsgs.push({ complete: true })
);

const s2 = recieved.subscribe(
  (msg) => sentMsgs.push({ next: msg }),
  (err) => sentMsgs.push({ error: err }),
  () => sendMsgs.push({ complete: true })
);


// to send a message
// (presumably whatever system you're injecting this into is doing the sending)
sent.next('weee');

// to mock a received message
received.next('blarg');

s1.unsubscribe();
s2.unsubscribe();

也就是说,这实际上取决于您要测试的内容、它的结构以及 API 是什么。

理想情况下,您可以 运行 同步进行整个测试。如果你因为某些与 Rx 相关的原因不能,你应该查看 TestScheduler,它有在虚拟化时间进行 运行 测试的设施。