【发布时间】: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