Marble-Testing Pattern
Learn the concepts of the marble-testing pattern.
We'll cover the following...
The marble diagram in code
Marble diagrams are very useful for visualizing observable execution. We learned about marble diagrams in The Power of the Reactive Paradigm, and we’ve used them in almost all the reactive patterns we’ve implemented in this course. At this point, I think we’re very familiar with marble diagrams. They’re simple to understand and delightful to read. So why not also use them in code? What you’ll be surprised to know is that RxJS introduced marble testing as an intuitive and clean way to test observables.
Let’s discover what marble testing is about. We’ll start by explaining the syntax in the next section and then learn how we can write marble tests in our code.
Understanding the syntax
To understand the syntax, we should know the following semantics:
Syntax Meaning
Character | Meaning |
' ' | This represents a special character that will not be intercepted. It can be used to align the marble string. |
' – ' | This represents a frame of visual time passing. |
' | ' | This represents the completion of an observable. |
[ a - z ] | This represents a value that’s emitted by an observable. It’s an alphanumeric character. |
' # ' | This represents an error. |
' ( ) ' | This represents a group of events that are occurring in the same frame. It can be used to group values emitted, errors, and completed. |
' ^ ' | This represents the subscription point and will only be used when we’re dealing with hot observables. |
[0 - 9] + [ms | s | m] | This represents the time progression. This allows us to progress virtual time by a specific amount. It’s a number followed by a unit in milliseconds (ms), seconds (s), or minutes (m) without any space between them. |
This is the basic syntax. Let’s look at some examples to practice the syntax:
— - -
: This represents an observable that never emits.-x--y--z|
: This represents an observable that waits one frame, emitsx
on frame 1,y
on frame 4, andz
on frame 7. After emittingz
, the observable completes.--xy--#
: This represents an observable that emitsx
on frame ...