【问题标题】:Jasmine how to put expectation on object returned from spied methodJasmine 如何对从间谍方法返回的对象寄予期望
【发布时间】:2020-04-26 12:58:22
【问题描述】:

我试图对调用某个函数“upsertDocument”的次数进行预期。在生产中,此方法是getClient 方法返回的DocumentClient 对象的一部分。即

单独的 client.ts 文件:

getClient() {
    return new DocumentClient(...);
}

在我要单元测试的方法中:

import * as clientGetter from '../clients/client'
...
methodA(){
  ...
  client = clientGetter.getClient(); 
  for (...) {
    client.upsertDocument();
  }
}

问题在于DocumentClient 构造函数初始化了与数据库的实际连接,这显然不应该在单元测试中发生。所以我要么需要监视 DocumentClient 构造函数,要么监视 getClient 方法,这两种方法都不起作用。

如果我监视 DocumentClient 构造函数:

单元测试:

it('does stuff', (done: DoneFn) => {
  spyOn(DocumentClient, 'prototype').and.returnValue({
    upsertDocument: () => {}
  })

  ...
})

我收到以下错误:

  Message:
    Error: <spyOn> : prototype is not declared writable or has no setter
    Usage: spyOn(<object>, <methodName>)
  Stack:
    Error: <spyOn> : prototype is not declared writable or has no setter
    Usage: spyOn(<object>, <methodName>)
        at <Jasmine>
        at UserContext.fit (C:\Users\andalal\workspace\azure-iots-saas\service-cache-management\src\test\routes\managementRoute.spec.ts:99:35)
        at <Jasmine>
        at runCallback (timers.js:810:20)
        at tryOnImmediate (timers.js:768:5)
        at processImmediate [as _immediateCallback] (timers.js:745:5)

如果我监视 getClient 方法并返回 我自己的 对象,其中包含一个 upsertDocument 方法,我不知道如何对那个模拟对象进行期望:

it('does stuff', (done: DoneFn) => {
  spyOn(clientGetter, 'getClient').and.returnValue({
    upsertDocument: () => {}
  })

  methodA().then(() => {
    expect().toHaveBeenCalledTimes(3); // what do I put in expect() ??
  })
})

【问题讨论】:

    标签: typescript jasmine


    【解决方案1】:

    似乎这个问题已经被现有的单元测试解决了,但我会在这里写一个解决方案,希望能帮助其他人:

    所以getClient 方法返回一个包含特定方法列表的 DocumentClient。我们不希望调用实际的 DocumentClient 构造函数。所以我们创建了一个模拟对象,它实现了与 DocumentClient 相同的接口,并在每个方法上使用了jasmine.createSpy

    export class TestableDocumentClient implements IDocumentClient {
      upsertDocument = jasmine.createSpy('upsertDocument')
      ...
    }
    

    然后在我的单元测试中,我窥探到了getClient 方法并返回了一个上述类型的对象:

    let mockDocClient = new TestableDocumentClient()
    spyOn(clientGetter, getClient).and.returnValue(mockDocClient);
    
    ...
    
    expect(mockDocClient.upsertDocument).toHaveBeenCalledTimes(3);
    

    为了理智,我做了一个简单的对象,它只有我想要的方法,并尝试对它设置一个期望,看看它是否有效,并且确实有效。

    let myObj = {
      upsertDocument: jasmine.createSpy('upsertDocument')
    }
    
    spyOn(clientGetter, 'getClient').and.returnValue(myObj);
    
    ...
    expect(myObj.upsertDocument).toHaveBeenCalledTimes(3);
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-13
      • 2022-10-22
      • 2012-05-04
      • 1970-01-01
      • 2022-10-04
      • 2011-08-26
      • 1970-01-01
      相关资源
      最近更新 更多