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

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

问题描述:

我有一些接受RxJS主题(支持套接字),我想测试的功能。我想以非常请求的回复方式嘲笑这个话题。由于我不确定干净的Rx方式来做到这一点,我很想用EventEmitter来形成我的假套接字。如何使用RxJS主题进行模拟和测试?

一般情况下,我想:

  • 支票,对我的“窝”匹配期望收到消息
  • 回应称消息就同一议题:observer.next(resp)

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


被测试的代码是

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; 
} 

您可以手动创建两个科目和“粘在一起”作为一个主题与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,它有虚拟化时间运行测试的功能。