我试图期望某个函数“ upsertDocument”被调用的次数。在生产中,此方法是DocumentClient
方法返回的getClient
对象的一部分。即
单独的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() ??
})
})
答案 0 :(得分:0)
现有的单元测试似乎已经解决了这个问题,但是我将在此处编写一个希望对其他人有所帮助的解决方案:
因此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);