Issue
I am trying to Unit Test a file using Nest.js (and Jest), like so:
import { Test, TestingModule } from '@nestjs/testing';
import { MyService } from 'myService';
import { DependencyService } from 'dependencyService';
describe('#mainMethod', () => {
let myService, dependencyService;
beforeAll(async () => {
let mockDependencyService = {
method1: jest.fn(() => true)
};
const module: TestingModule = await Test.createTestingModule({
providers: [
MyService,
DependencyService,
]
})
.overrideProvider(DependencyService).useValue(mockDependencyService)
.compile();
myService = module.get<MyService>(MyService);
dependencyService = module.get<DependencyService>(DependencyService);
});
it('should be ok', () => {
// any test
})
});
When writing it like that, I am able to test a scenario where method1
from DependencyService
returns true
.
What is the best way of testing a different response from method1
? Should I wrap it all in a BeforeEach
, create another describe
block, change the mockDependencyService.method1
's return, and create the module all over again? Is there a better way to do it?
Thanks!
Solution
I would probably mock the module like so as a normal function:
let mockDependencyService = {
method1: () => true
};
And then spy on the instance from each test:
jest.spyOn(myService, 'method1').mockReturnValue(false)
myService.method1()
// useless expectation for demo purposes
expect(myService.method1).toHaveBeenCalled()
This lets you prep the starting circumstances for each test as each test needs.
Answered By - Alex Wayne
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.