如何在RxJS大理石测试中找到hot与cold操作符?求示例
hot and cold Operators + Example Great question! I remember scratching my head over this when I first dove into RxJS marble testing—those operators aren't hanging around in the main RxJS library, they're purpose-built for testing. Let's get you sorted:
1. First, Install the Testing Dependency
The hot and cold functions live in the @rxjs/testing package, which is separate from the core RxJS library. If you haven't already, install it as a dev dependency:
npm install --save-dev @rxjs/testing # Or with Yarn: yarn add --dev @rxjs/testing
2. Access hot/cold via TestScheduler
These functions aren't global—you'll get them through the TestScheduler's run() method. This method wraps your test logic and injects all the marble testing utilities you need (including hot, cold, and expectObservable) directly into your callback.
Full Example (Using Jest/Jasmine)
Here's a concrete test that uses both hot and cold to verify a simple transformation with map:
import { TestScheduler } from '@rxjs/testing'; import { map } from 'rxjs/operators'; describe('RxJS Marble Test Demo', () => { let testScheduler: TestScheduler; // Set up the scheduler before each test beforeEach(() => { testScheduler = new TestScheduler((actual, expected) => { // Use your testing framework's assertion here expect(actual).toEqual(expected); }); }); it('should double values emitted by a hot observable', () => { testScheduler.run(({ hot, expectObservable }) => { // Create a HOT observable (simulates a shared stream like user input) const input$ = hot('-a-b-c-|', { a: 1, b: 2, c: 3 }); // Apply our transformation const output$ = input$.pipe(map(num => num * 2)); // Define what we expect to see expectObservable(output$).toBe('-x-y-z-|', { x: 2, y: 4, z: 6 }); }); }); it('should handle a cold observable (like an API call)', () => { testScheduler.run(({ cold, expectObservable }) => { // Create a COLD observable (simulates a stream that restarts on each subscription) const apiResponse$ = cold('--a-|', { a: 'data from API' }); expectObservable(apiResponse$).toBe('--a-|', { a: 'data from API' }); }); }); });
Quick Notes on hot vs cold
hot(): Use this for streams that are already "live" when your test runs—think DOM events, WebSocket connections, or global state changes. Subscribing to a hot observable picks up emissions from the current point in time, not the start.cold(): Use this for streams that start fresh every time they're subscribed to—like API requests, timers, or internal data fetchers. Each subscription to a cold observable will receive all emissions from the beginning.
Marble Syntax Cheat Sheet (Quick Recap)
-: 1 time frame (you can think of this as a millisecond in test time)a/b/c: Emitted values (mapped to the object you pass as the second argument)|: Stream completes successfully#: Stream emits an error
内容的提问来源于stack exchange,提问作者Thomas Betous

