Issue
I'm trying to mock a private, class-level instance property so that I can assert on it to see if it is being called. In this particular case it is a NestJs Logger instance, but I believe the question is a broader one.
Here is the class under test:
import { Logger } from '@nestjs/common';
export class SomeService {
private readonly logger = new Logger(SomeService.name);
methodUnderTest(someNumber: number): string {
if (someNumber === 5) {
return 'Greater';
else {
this.logger.error('It is definitely not 5.');
}
}
}
And here is my (attempt at a) test class:
import { Logger } from '@nestjs/common';
jest.mock('@nestjs/common'); // This is causing the error below.
const someService = new SomeService();
describe('SomeService - methodUnderTest', () => {
it('should call logger.error when someNumber is not 5', () => {
someService.methodUnderTest(2);
expect(Logger.error).toHaveBeenCalled(); // This is incorrect.
}
}
I know this isn't correct. I was wondering if I had to use a spy, but wasn't sure how to make that work. Currently I'm receiving this error upon execution of the test:
● Test suite failed to run
TypeError: index_1.Injectable is not a function
at Object.<anonymous> (../.yarn/__virtual__/@nestjs-common-virtual-992fab1572/0/cache/@nestjs-common-npm-8.2.4-cc0ecb2b32-a2945b7fb7.zip/node_modules/@nestjs/common/pipes/parse-float.pipe.js:40:13)
at Object.<anonymous> (../.yarn/__virtual__/@nestjs-common-virtual-992fab1572/0/cache/@nestjs-common-npm-8.2.4-cc0ecb2b32-a2945b7fb7.zip/node_modules/@nestjs/common/pipes/index.js:8:22)
Solution
The answer was indeed to use a spy. The error was being thrown by this line, which is not needed at all actually:
jest.mock('@nestjs/common');
Here's the working solution; quite simple in the end:
import {describe, expect, it, jest } from '@jest/globals';
import { Logger } from '@nestjs/common';
const loggerSpy = jest.spyOn(Logger.prototype, 'error');
const someService = new SomeService();
describe('SomeService - methodUnderTest', () => {
it('should call logger.error when someNumber is not 5', () => {
someService.methodUnderTest(2);
expect(loggerSpy).toHaveBeenCalled();
}
}
Answered By - risingTide
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.