首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jest的大理石测试失败,但Jasmine的等效测试成功

Jest的大理石测试失败,但Jasmine的等效测试成功
EN

Stack Overflow用户
提问于 2019-04-16 17:38:16
回答 1查看 1.1K关注 0票数 3

我正在尝试将我的单元测试从Jasmine转换为Jest。一些测试在转换为Jest后开始失败。有人能解释一下为什么他们在Jest上失败了吗?

我设法将问题隔离到下面的测试用例中。

使用Jasmine is成功运行:

代码语言:javascript
复制
import { JasmineMarble } from './jasmine-marble';
import { cold } from 'jasmine-marbles';
import { switchMap } from 'rxjs/operators';
import { EMPTY, Observable } from 'rxjs';

class Service {
  foo(): Observable<any> {
    return EMPTY;
  }

  bar(a): Observable<any> {
    return EMPTY;
  }
}

describe('JasmineMarble', () => {
  it('should create an instance', () => {
    const service = new Service();

    spyOn(service, 'foo').and.returnValue(cold('a|', { a: 'A' }));
    spyOn(service, 'bar').and.returnValue(cold('a-b-c|', { a: 'A', b: 'B', c: 'C'}));

    const result$ = service.foo().pipe(switchMap(a => service.bar(a)));

    expect(result$).toBeObservable(cold('a-b-c|', { a: 'A', b: 'B', c: 'C'}));
    expect(service.bar).toHaveBeenCalledWith('A');
  });
});

对于Jest,它会失败,并显示以下错误跟踪:

代码语言:javascript
复制
expect(jest.fn()).toHaveBeenCalledWith(expected)

Expected mock function to have been called with:
  ["A"]
But it was not called.

Jest代码:

代码语言:javascript
复制
import { JestMarble } from './jest-marble';
import { cold } from 'jest-marbles';
import { switchMap } from 'rxjs/operators';
import { EMPTY, Observable } from 'rxjs';

class Service {
  foo(): Observable<any> {
    return EMPTY;
  }

  bar(a): Observable<any> {
    return EMPTY;
  }
}

describe('JestMarble', () => {
  it('should create an instance', () => {
    const service = new Service();

    jest.spyOn(service, 'foo').mockReturnValue(cold('a|', { a: 'A' }));
    jest.spyOn(service, 'bar').mockReturnValue(cold('a-b-c|', { a: 'A', b: 'B', c: 'C'}));

    const result$ = service.foo().pipe(switchMap(a => service.bar(a)));

    expect(result$).toBeObservable(cold('a-b-c|', { a: 'A', b: 'B', c: 'C'}));
    expect(service.bar).toHaveBeenCalledWith('A');
  });
});

有人能解释这种行为吗?

您可以在这里找到示例存储库:https://github.com/stijnvn/marbles可以使用ng test jasmine-marbles运行Jasmine示例。和ng test jest-marbles一起开玩笑的那个。

EN

回答 1

Stack Overflow用户

发布于 2020-11-18 01:31:16

现在引入了toSatisfyOnFlush来处理这个问题:

代码语言:javascript
复制
describe('JestMarble', () => {
  it('should create an instance', () => {
    const service = new Service();

    jest.spyOn(service, 'foo').mockReturnValue(cold('a|', { a: 'A' }));
    jest.spyOn(service, 'bar').mockReturnValue(cold('a-b-c|', { a: 'A', b: 'B', c: 'C'}));

    const result$ = service.foo().pipe(switchMap(a => service.bar(a)));

    expect(result$).toBeObservable(cold('a-b-c|', { a: 'A', b: 'B', c: 'C'}));
    expect(output$).toSatisfyOnFlush(() => {
      expect(service.bar).toHaveBeenCalledWith('A');
    });
  });
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55705040

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档