标签: rxjs-marbles

使用 RxJS Marbles 测试 Angular Reactive Forms

角度组件

public setupObservables() {
  this.formFieldChanged$ = this.formField
    .valueChanges
    .pipe(
        debounceTime(100),
        distinctUntilChanged((a, b) => a === b),
    )
}
Run Code Online (Sandbox Code Playgroud)

茉莉花测试

import { of } from 'rxjs';
import { marbles } from 'rxjs-marbles/jasmine';  
...

it('should update value on debounced formField change', marbles(m => {
  const values = { a: "1", b: "2", c: "3" };

  const fakeInputs = m.cold('a 200ms b 50ms c', values);
  const expected = m.cold('100ms a 250ms c', values);

  // works on stackblitz but otherwise gives TS2540 compiler error …
Run Code Online (Sandbox Code Playgroud)

jasmine rxjs angular rxjs-marbles

8
推荐指数
1
解决办法
514
查看次数

带延迟测试 NGRX 效果

我想测试一下效果如下:

  1. 如果调度了 LoadEntriesSucces 操作,则效果开始
  2. 等待5秒
  3. 5 秒后发送 http 请求
  4. 当响应到达时,将调度新的操作(取决于响应是成功还是错误)。

Effect 的代码如下所示:

  @Effect()
  continuePollingEntries$ = this.actions$.pipe(
    ofType(SubnetBrowserApiActions.SubnetBrowserApiActionTypes.LoadEntriesSucces),
    delay(5000),
    switchMap(() => {
      return this.subnetBrowserService.getSubnetEntries().pipe(
        map((entries) => {
          return new SubnetBrowserApiActions.LoadEntriesSucces({ entries });
        }),
        catchError((error) => {
          return of(new SubnetBrowserApiActions.LoadEntriesFailure({ error }));
        }),
      );
    }),
  );
Run Code Online (Sandbox Code Playgroud)

我想测试的是5秒后是否发出效果:

it('should dispatch action after 5 seconds', () => {
  const entries: SubnetEntry[] = [{
    type: 'type',
    userText: 'userText',
    ipAddress: '0.0.0.0'
  }];

  const action = new SubnetBrowserApiActions.LoadEntriesSucces({entries});
  const completion = new SubnetBrowserApiActions.LoadEntriesSucces({entries});

  actions$ = hot('-a', { …
Run Code Online (Sandbox Code Playgroud)

rxjs ngrx ngrx-effects jasmine-marbles rxjs-marbles

8
推荐指数
1
解决办法
5846
查看次数

在 RxJs 和 Angular 中测试可观察的“下一个”回调

我正在尝试使用 RxJs Observables 在 Angular 中做一个非常简单的测试,但我做的很短。这就是我基本上要测试的内容:

// We're inside some Angular component here...
let testMe = 0;

function somethingOrOther(): void {

    this.someService.methodReturningObservable()
      .subscribe(
          (nextValue: number): void => {
              testMe += nextValue;
          }
      ) 
}
Run Code Online (Sandbox Code Playgroud)

testMe当后面的 observablemethodReturningObservable发出值时,如何测试是否正确更新?

我用这个尝试过:

it(`works 'cuz I want it to`, fakeAsync(() => {
    spyOn(this.someService, 'methodReturningObservable').and.returnValue(cold('a', {a: 10}));

    tick();

    expect(component.testMe).toBe(10);
}));
Run Code Online (Sandbox Code Playgroud)

所以,tick()这里似乎没有做任何事情。没有什么能让我cold对我的间谍发出任何价值。

我尝试了getTestScheduler.flush(),如弹珠部分下的https://netbasal.com/testing-observables-in-angular-a2dbbfaf5329所示。

我可以使用这样的弹珠在 observable 上发出值吗?这在 AngularJS 中非常容易,只需触发一个摘要,但我似乎无法让 Anguar 让我进入下一个可观察的回调。

rxjs angular jasmine-marbles rxjs-marbles

5
推荐指数
1
解决办法
1654
查看次数

如何在 Angular 中通过 graphQL Apollo 测试控制器使用 rxjs 弹珠测试

我想在 Angular 中测试 GraphQL 订阅

  1. 进行查询
  2. 使用以下命令将订阅附加到查询subscribeToMore
  3. 通过在其操作中使用flush来模拟查询结果并验证结果
  4. 通过在其操作上使用flush来模拟订阅结果并验证结果

我按照有关客户端测试的 Apollo 文档成功地进行了良好的测试:

const ENTITY_QUERY = gql`
  query EntityList {
    entityList {
      id
      content
    }
  }
`;

const ENTITY_SUBSCRIPTION = gql`
  subscription OnNameChanged {
    nameChanged {
      id
      name
    }
  }
`;

describe('Test Subscription', () => {
  let backend: ApolloTestingController;
  let apollo: Apollo;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ApolloTestingModule],
      providers: [
        {
          provide: APOLLO_TESTING_CACHE,
          useValue: new InMemoryCache({ addTypename: true })
        }
      ]
    });
    backend = TestBed.get(ApolloTestingController);
    apollo = TestBed.get(Apollo); …
Run Code Online (Sandbox Code Playgroud)

rxjs apollo graphql angular rxjs-marbles

5
推荐指数
0
解决办法
590
查看次数

当返回实际上是 EMPTY 可观察值时,如何使用大理石方法进行测试?

我使用 rxjs 中的 EMPTY 来处理 catchError,为了通过失败场景,预期的正确值是多少。

import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { EMPTY } from 'rxjs';
import { map, mergeMap, catchError } from 'rxjs/operators';
import { MoviesService } from './movies.service';

@Injectable()
export class MovieEffects {

  loadMovies$ = createEffect(() => this.actions$.pipe(
    ofType('[Movies Page] Load Movies'),
    mergeMap(() => this.moviesService.getAll()
      .pipe(
        map(movies => ({ type: '[Movies API] Movies Loaded Success', payload: movies })),
        catchError(() => EMPTY)
      ))
    )
  );

  constructor(
    private actions$: Actions, …
Run Code Online (Sandbox Code Playgroud)

javascript jasmine rxjs5 ngrx-effects rxjs-marbles

5
推荐指数
1
解决办法
2210
查看次数

RxJS mixLatest 每个路径仅发出一次

是否有任何方法/模式可以使用combineLatest()或其他一些运算符,以便如果组合的可观察量相互依赖,则它们对于 DAG 中具有相同原点的每组路径仅发出一次?我想用图可能更容易解释。

图表:

   A C
  /| |
 B | |
  \|/
   D
Run Code Online (Sandbox Code Playgroud)

这里 B 订阅了 A,D 订阅了 A、B 和 C。默认行为是,如果 A 发出,D 发出两次:当 A 发出时一次,当 B 发出时再一次(由于 A 发出) )。我希望它在两者都发射后只发射一次。然而,如果 C 发出,那么 D 也应该立即发出。

这是代码:

const A = new Rx.BehaviorSubject(1);
const B = A.pipe(Rx.map((x) => x + 1));
const C = new Rx.BehaviorSubject(3);

const D = Rx.combineLatest({ A, B, C });

D.subscribe(console.log); // {A: 1, B: 2, C: 3}
A.next(2); // Two emissions: …
Run Code Online (Sandbox Code Playgroud)

javascript rxjs rxjs-marbles

5
推荐指数
1
解决办法
412
查看次数

Angular 单元测试:如何使用弹珠测试(rxjs/testing)来测试这个状态管理服务

在我的 angular 项目中,我有一个服务,用于状态管理以在组件之间共享一些数据,如下所示:

@Injectable({ providedIn: "root"})
export class NameStateService {

    private _filteredNames$: Subject<Name[]> = new Subject();
    private _filteredNamesObs$: Observable<Name[]>;

    constructor() {
        this._filteredNamesObs$ = this._filteredNames$.asObservable();
    }

    public updateFilteredNames(val: Name[]): void {
        this._filteredNames$.next(val);
    }

    public get filteredNames$(): Observable<BillingAccount[]> {
        return this._filteredNamesObs$;
    }
}
Run Code Online (Sandbox Code Playgroud)

状态管理基于主题和可观察,这是 rxjs 世界中的典型用法。

而对于这个服务的单元测试,我想使用rxjs/testing模块支持的弹珠测试功能。解决方法如下:

describe("Name state service ", () => {
    let nameStateService: NameStateService;
    let scheduler: TestScheduler;

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                NameStateService
            ]
        });
        nameStateService = TestBed.get(NameStateService);
        scheduler = new TestScheduler((actual, expected) => expect(actual).toEqual(expected));
    }); …
Run Code Online (Sandbox Code Playgroud)

unit-testing rxjs angular jasmine-marbles rxjs-marbles

4
推荐指数
1
解决办法
2053
查看次数

RxJs 弹珠测试:断言失败日志难以理解

我有这个 Rxjs 测试代码。它故意失败,因为我想向您展示失败的日志。我发现这很难理解,或者至少我不能流利地阅读它。

有人可以解释我什么意思:$[i].frame = i' to equals i''

import { delay } from 'rxjs/operators';
import { TestScheduler } from 'rxjs/testing';

describe('Rxjs Testing', () => {

  let s: TestScheduler;

  beforeEach(() => {
    s = new TestScheduler((actual, expected) => {
      expect(actual).toEqual(expected);
    });
  });

  it('should not work', () => {
    s.run(m => {
      const source = s.createColdObservable('-x-y-z|');
      const expected = '-x-y-z|'; // correct expected value is '---x-y-z|'

      const destination = source.pipe(delay(2));
      m.expectObservable(destination).toBe(expected);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

testing rxjs rxjs6 rxjs-marbles

4
推荐指数
1
解决办法
1680
查看次数