I am currently faced with setting an expectation regarding the number of times a specific function called "upsertDocument" is executed. This function is part of a DocumentClient
object within a getClient
method in production. Here's how it looks:
client.ts file:
getClient() {
return new DocumentClient(...);
}
In the method I aim to unit test:
import * as clientGetter from '../clients/client'
...
methodA(){
...
client = clientGetter.getClient();
for (...) {
client.upsertDocument();
}
}
The issue arises from the fact that the DocumentClient
constructor establishes a live connection with the database, which obviously isn't suitable for unit testing. My options are either to spyOn the DocumentClient constructor or the getClient method, both of which present challenges.
If I spy on the DocumentClient constructor:
unit test:
it('performs specific actions', (done: DoneFn) => {
spyOn(DocumentClient, 'prototype').and.returnValue({
upsertDocument: () => {}
})
...
})
This results in the following error:
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)
If I spy on the getClient
method and provide my own object with an upsertDocument
method, I face difficulty in setting an expectation on that mock object:
it('performs specific actions', (done: DoneFn) => {
spyOn(clientGetter, 'getClient').and.returnValue({
upsertDocument: () => {}
})
methodA().then(() => {
expect().toHaveBeenCalledTimes(3); // what do I put in expect() ??
})
})