【问题标题】:How do I inject a different dependency mock into a service partway through the test suite for that service?如何通过该服务的测试套件将不同的依赖模拟注入服务中?
【发布时间】:2020-10-28 04:23:45
【问题描述】:

在测试 Angular 服务(具有自己的依赖项)时,我经常发现自己在测试套件中同时测试快乐路径和悲伤路径。

我的意思是我有这项服务:

export class MyService {
  constructor(private MyClient) {}

  public doIt() {
    return this.myClient.doTheThing().pipe(
      catchError(error => {
        // error handling logic
      }),
      // process the response
    )
  }
}

现在我想测试MyService#doItMyClient#doTheThing 成功运行并返回该请求的响应/结果的可观察值时,以及当MyClient#doTheThing 失败和错误时(因为我在@ 中有一些逻辑987654325@待测)。

测试幸福路径很简单:

// MyClientMock is a mock implementation of MyClient that returns a canned result 
// for instance so that I can test against these values when running the tests.

describe(MyService, () => {
  let service: MyService

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        MyService,
        { provide: MyClient, useClass: MyClientMock }
      ],
    })
    service = TestBed.inject(MyService)
  })

  it('does the thing', (done) => {
    service.doIt().subscribe(result => {
      expect(result).toEqual('something')
      done()
    })
  })
})

但是当MyClient 抛出错误时,我如何测试悲伤路径,并确保catchError 中的逻辑符合我的预期?

我想过创建另一个MyClientMock 并将其命名为MyClientErrorMock,它将抛出。但是我不能注入它,因为它在测试开始时就已经设置好了,它会干扰其他测试用例。

在这种情况下使用什么模式来测试依赖项错误或成功时会发生什么?

【问题讨论】:

    标签: angular unit-testing jestjs


    【解决方案1】:

    我强烈推荐 Jest 而不是 Karma。

    当您需要重新创建模拟函数的复杂行为以使多个函数调用产生不同的结果时,请使用 mockImplementationOnce 方法:

    const myMockFn = jest
      .fn()
      .mockImplementationOnce(cb => cb(null, true))
      .mockImplementationOnce(cb => cb(null, false));
    
    myMockFn((err, val) => console.log(val));
    // > true
    
    myMockFn((err, val) => console.log(val));
    // > false
    

    这是另一个模拟示例,它根据条件参数生成结果:

    import { when } from 'jest-when';
    
    const fn = jest.fn();
    when(fn).calledWith(1).mockReturnValue('hello world!');
    
    const result = fn(1);
    expect(result).toEqual('hello world!');
    

    我想说,Jest 相对于 Karma 的最大优势在于其不隐晦、直截了当的错误消息,让您一眼就能确定测试失败的根本原因。

    【讨论】:

    • 谢谢,很有帮助!
    猜你喜欢
    • 1970-01-01
    • 2019-12-08
    • 2013-04-07
    • 2020-09-09
    • 2012-12-23
    • 1970-01-01
    • 2016-01-26
    • 2020-01-02
    • 1970-01-01
    相关资源
    最近更新 更多