I've inherited a JS application (Node). JS is not my strongest suit, and definitely not Promises. I've been tasked to bring the code up to modern standards, i.e. using classes and async/await. I am trying to be a good developer and create unit tests as well. Calls to the db have been pulled out into a separate persistor
class, which the intent is to mock. However, the mock I created does not seem to work. It appears that the await
is not waiting, so likely something wrong with the way I am mocking. The test fails with expected {} to deeply equal { Object (status, method, ...) }
.
Here is my mock persistor.
const mockPersistor = {
getModels: function getModels() {
RootLogger.debug('mockPersistor.getModels()');
return {
Category: 'Category',
Attribute: 'Attribute',
Option: 'Option'
};
},
setModels: function setModels() {
RootLogger.debug('mockPersistor.setModels()');
},
findXref: function findXref(model, conditions) {
RootLogger.debug(`mockPersistor.findXref(${model}, ${JSON.stringify(conditions)})`);
return new Promise((resolve, reject) => {
return {
status: 'success',
method: `findXref`,
model: `${model}`,
conditions: `${conditions}`
};
});
}
};
The method under test is:
async getMagentoCategoryByNetSuiteId(netSuiteId, netSuiteRecordName) {
this.log.debug(`SystemXrefCache.getMagentoCategoryByNetSuiteId(${netSuiteId}, ${netSuiteRecordName})`);
const result = await this.findXref(
this.models.Category,
{
netSuiteId: JSON.parse(netSuiteId),
netSuiteRecordName: netSuiteRecordName
}
);
return result;
}
The findXref method only redirects to the new persistor class method I've created (for greater refactoring purposes) of the same name:
async findXref(model, conditions) {
this.log.debug(`SystemXrefCache.findXref(${JSON.stringify(model)}, ${JSON.stringify(conditions)})`);
return await this.persistor.findXref(model, conditions);
}
I have tried several variations of creating a promise in the mock, all to no avail. I have async/await all down the line - unless I am just missing the obvious, so that should not be the problem.
So, perhaps the problem is in the test itself? I have tried a few things here as well, but this is my latest:
it('getMagentoCategoryByNetSuiteId returns successfully', function() {
RootLogger.debug(`=== starting test getMagentoCategoryByNetSuiteId returns successfully ===`);
const givenNetsuiteId = `99`;
const givenNetsuiteRecordName = `recordName`;
const expected = {
status: 'success',
method: `findXref`,
model: `Category`,
conditions: {
netSuiteId: 99,
netSuiteRecordName: `recordName`
}
};
const result = cache.getMagentoCategoryByNetSuiteId(
givenNetsuiteId,
givenNetsuiteRecordName
).then( resp => {
RootLogger.debug(`=== call completed!!! ===`);
return resp;
});
expect(result).to.deep.equal(expected);
});