Marble testing is an expressive way to test observables by utilizing marble diagrams. This lesson will walk you through the syntax and features, preparing you to start writing marble tests today!

Grep two files from the rxjs

  • https://github.com/ReactiveX/rxjs/blob/master/spec/helpers/marble-testing.ts
  • https://github.com/ReactiveX/rxjs/blob/master/spec/helpers/test-helper.ts
/*
RxJS marble testing allows for a more natural style of testing observables.
To get started, you need to include a few helpers libraries, marble-testing.ts and test-helper.ts,
in your karma.conf or wallaby.js configuration file.
These files provide helpers for parsing marble diagrams and asserting against the subscription points and result
of your observables under test. For these examples I will be using Jasmine, but Mocha and Chai works just as well. Let's get started with the basics of marble testing! First, let's understand the pieces that make up a valid marble diagram. Dash: Indicates a passing of time, you can think of each dash as 10ms when it comes to your tests.
----- <----- 50ms
Characters: Each character inside the dash indicates an emission.
-----a-----b-----c <----- Emit 'a' at 60ms, 'b' at 120ms, 'c' at 180ms
Pipes |: Pipes indicate the completion point of an observable.
-----a| <----- Emit 'a' at 60ms then complete (70ms)
Parenthesis (): Parenthesis indicate multiple emissions in same time frame, think Observable.of(1,2,3)
-----(abc|) <----- Emit 'a''b''c' at 60ms then complete (60ms)
Caret ^: Indicates the starting point of a subscription, used with expectSubscription assertion.
^------- <----- Subscription point at caret.
Exclamation Point - !: Indicates the end point of a subscription, also used with expectSubscription assertion.
^------! <----- Subscription starts at caret, ends at exclamation point.
Pound Sign - #: Indicates an error
---a---# <----- Emit 'a' at 40ms, error at 80ms
There are also a few methods included to parse marble sequences and transpose values. cold(marbles: string, values?: object, error?: any) : Subscription starts when test begins
cold(--a--b--|, {a: 'Hello', b: 'World'}) <----- Emit 'Hello' at 30ms and 'World' at 60ms, complete at 90ms
hot(marbles: string, values?: object, error?: any) : Behaves like subscription starts at point of caret
hot(--^--a---b--|, {a: 'Goodbye', b: 'World'}) <----- Subscription begins at point of caret
*/

For example we want to test:

const source =       "---a---b---c--|";
const expected = "---a---b---c--|";

they should be equal.

Here each '-' means 1. frames.

'|' means completed.

The method we need to use is 'expectObservable' & 'cold':

    it('should parse marble diagrams', () => {
const source = cold('---a---b---c---|');
const expected = '---a---b---c---|'; expectObservable(source).toBe(expected)
});

Cold will treat the beginning of the diagram as a subscription point. Now the test passing.

But if we change a little bit:

    it('should parse marble diagrams', () => {
const source = cold('---a---b---c---|');
const expected = '---a--b---c---|'; expectObservable(source).toBe(expected)
});

It reports error:

    Expected
{"frame":30,"notification":{"kind":"N","value":"a","hasValue":true}}
{"frame":,"notification":{"kind":"N","value":"b","hasValue":true}}
{"frame":,"notification":{"kind":"N","value":"c","hasValue":true}}
{"frame":,"notification":{"kind":"C","hasValue":false}} to deep equal
{"frame":30,"notification":{"kind":"N","value":"a","hasValue":true}}
{"frame":,"notification":{"kind":"N","value":"b","hasValue":true}}
{"frame":,"notification":{"kind":"N","value":"c","hasValue":true}}
{"frame":,"notification":{"kind":"C","hasValue":false}}

Test 'concat' opreator:

    it('should work with cold observables', () => {
const obs1 = cold('-a---b-|');
const obs2 = cold('-c---d-|');
const expectedConcatRes = '-a---b--c---d-|'; expectObservable(obs1.concat(obs2)).toBe(expectedConcatRes)
});

'Hot' observable: Hot will actually let you identify the subscription point yourself:

When testing hot observables you can specify the subscription point using a caret '^', similar to how you specify subscriptions when utilizing the expectSubscriptions assertion.

    it('should work with hot observables', () => {
const obs1 = hot('---a--^--b---|');
const obs2 = hot('-----c---^-----------------d-|');
const expected = '---b--------------d-|'; expectObservable(obs1.concat(obs2)).toBe(expected);
});

Algin the ^, easy for read

Spread subscription and marble diagram:

    /*
For certain operators you may want to confirm the point at which
an observable is subscribed or unsubscribed. Marble testing makes this
possible by using the expectSubscriptions helper method. The cold and hot
methods return a subscriptions object, including the frame at which the observable
would be subscribed and unsubscribed. You can then assert against these
subscription points by supplying a diagram which indicates the expected behavior. ^ - Indicated the subscription point.
! - Indicates the point at which the observable was unsubscribed. Example subscriptions object: {"subscribedFrame":70,"unsubscribedFrame":140}
*/
it('should identify subscription points', () => {
const obs1 = cold('-a---b-|');
const obs2 = cold('-c---d-|')
const expected = '-a---b--c---d-|';
const sub1 = '^------!'
const sub2 = '-------^------!' expectObservable(obs1.concat(obs2)).toBe(expected);
expectSubscriptions(obs1.subscriptions).toBe(sub1);
expectSubscriptions(obs2.subscriptions).toBe(sub2);
})

Object to map the key and value:

    /*
Both the hot and cold methods, as well the the toBe method accept an object map as a
second parameter, indicating the values to output for the appropriate placeholder.
When the test is executed these values rather than the matching string in the marble diagram.
*/
it('should correctly sub in values', () => {
const values = {a: 3, b: 2};
const source = cold( '---a---b---|', values);
const expected = '---a---b---|'; expectObservable(source).toBe(expected, values);
});
    /*
Multiple emissions occuring in same time frame can be represented by grouping in parenthesis.
Complete and error symbols can also be included in the same grouping as simulated outputs.
*/
it('should handle emissions in same time frame', () => {
const obs1 = Observable.of(1,2,3,4);
const expected = '(abcd|)'; expectObservable(obs1).toBe(expected, {a: 1, b: 2, c: 3, d: 4});
});
    /*
For asynchronous tests RxJS supplies a TestScheduler.
How it works...
*/
it('should work with asynchronous operators', () => {
const obs1 = Observable
.interval(10, rxTestScheduler)
.take(5)
.filter(v => v % 2 === 0);
const expected = '-a-b-(c|)'; expectObservable(obs1).toBe(expected, {a: 0, b: 2, c: 4});
});

Error handling:

    /*
Observables that encounter errors are represented by the pound (#) sign.
In this case, our observable is retried twice before ultimately emitting an error.
A third value can be supplied to the toBe method specifying the error to be matched.
*/
it('should handle errors', () => {
const source = Observable.of(1,2,3,4)
.map(val => {
if(val > 3){
throw 'Number too high!';
};
return val;
})
.retry(2); const expected = '(abcabcabc#)'; expectObservable(source).toBe(expected, {a: 1, b: 2, c: 3, d: 4}, 'Number too high!');
});

[RxJS] Introduction to RxJS Marble Testing的更多相关文章

  1. [AngularJS + RxJS] Search with RxJS

    When doing search function, you always need to consider about the concurrent requests. AEvent ----(6 ...

  2. [RxJS] Split an RxJS Observable into groups with groupBy

    groupBy() is another RxJS operator to create higher order observables. In this lesson we will learn ...

  3. [RxJS] Split an RxJS observable conditionally with windowToggle

    There are variants of the window operator that allow you to split RxJS observables in different ways ...

  4. [RxJS] Split an RxJS observable with window

    Mapping the values of an observable to many inner observables is not the only way to create a higher ...

  5. RxJS v6 学习指南

    为什么要使用 RxJS RxJS 是一套处理异步编程的 API,那么我将从异步讲起. 前端编程中的异步有:事件(event).AJAX.动画(animation).定时器(timer). 异步常见的问 ...

  6. RxJS速成 (上)

    What is RxJS? RxJS是ReactiveX编程理念的JavaScript版本.ReactiveX是一种针对异步数据流的编程.简单来说,它将一切数据,包括HTTP请求,DOM事件或者普通数 ...

  7. RxJS速成 (下)

    上一部分: http://www.cnblogs.com/cgzl/p/8641738.html Subject Subject比较特殊, 它即是Observable又是Observer. 作为Obs ...

  8. RxJS入门

    一.RxJS是什么? 官方文档使用了一句话总结RxJS: Think of RxJS as Lodash for events.那么Lodash主要解决了什么问题?Lodash主要集成了一系列关于数组 ...

  9. RxJS 6有哪些新变化?

    我们的前端工程由Angular4升级到Angular6,rxjs也要升级到rxjs6.  rxjs6的语法做了很大的改动,幸亏引入了rxjs-compact包,否则升级工作会无法按时完成. 按照官方的 ...

随机推荐

  1. 接入脚本interface.php实现代码

    承接上文的WeChatCallBack 在WeChatCallBack类的成员变量中定义了各种消息都会有的字段,这些字段在init函数中赋值.同时也把解析到的XML对象作为这个类的成员变量$_post ...

  2. 设置layoutControl1 中的 控件的 focus

    设置 layoutControl1 中的layoutControl EnableAutoTabOrder 为 false; this.layoutControl1.ActiveControl = th ...

  3. PackageManager获取版本号

    PackageInfo代表的是关于一个包的所有信息,就相当于一个APP应用的清单文件中收集到的所有信息. 通过这个类我们就可以获取类似版本号等一些信息. /** * 得到应用程序的版本名称 */ pr ...

  4. Android - LayoutInflater

    在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById().不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例 ...

  5. 新購電腦筆記 - G1.Sniper B7 內建網路晶片在 Mint 17.2(Cinnamon)上無法使用(已解決)

    又好久沒寫文章了,這次因新購電腦,有一些狀況,故做一下記錄,也分享給遇到同樣問題的格友 以前在公司裝 Ubuntu 從沒遇過這麼多問題,這次自己第一次組電腦,也第一次裝 Mint,問題倒是不少 第一個 ...

  6. Apache Spark Streaming的适用场景

    使用场景: Spark Streaming 适合需要历史数据和实时数据结合进行分析的应用场景,对于实时性要求不是特别高的场景也能够胜任.

  7. Argument 'xxx' is not a function, got undefined,初学Angular的第一个坑

    终于考完试了,在没更新的这一段时间里,一直都在忙于应付考试.不过在期间也是接触到不少好玩的东西,比如Html5的Canvas,我用lufylegend的Html5引擎做了个<看你有所色>的 ...

  8. WinJS.Binding.List与kendo.data.ObservableArray

    avalon0.8一个最大目标是实现对数组的深层监控,可是面临的困难重重,至今还没有什么起色.于是看一下其他两个MVVM框架的做法(knockout, emberjs, angular都不能监听家庭数 ...

  9. HDU 4882 ZCC Loves Codefires (贪心)

    ZCC Loves Codefires 题目链接: http://acm.hust.edu.cn/vjudge/contest/121349#problem/B Description Though ...

  10. memcached全面剖析–3. memcached的删除机制和发展方向

    memcached在数据删除方面有效利用资源 数据不会真正从memcached中消失 上次介绍过, memcached不会释放已分配的内存.记录超时后,客户端就无法再看见该记录(invisible,透 ...