Shallow Test Utility
On systems that rely on dependency injection, test can sometimes be hard to setup, and if you forget to mock a dependency of your class, you may end up instantiating it and making your test not be "Unitary" anymore.
Tht's what this package aims to solde, inspired on angular Shallow Renderer. You can easly, just with a ENUM that represents your class constructor parameters order, instantiate it with the certainty that all of your constructor dependencies will be empty, ready to mock.
How to Use
Supose you'll be testing this scenario:
class ServiceToTest {
constructor(private depA: DependencyA, private depB: DependencyB) {}
methodToTest() {
const aResult = this.depA.methodA();
const bResult = this.depB.methodB(aResult);
}
}
class DependencyA {
methodA() {
return Math.floor(Math.random() * 10 + 1)
}
}
class DependencyB {
methodB(number: number) {
return number * 10
}
}
Your test file need to Shallow instantiate your ServiceToTest
, and you can do it this way:
import { ServiceToTest } from '.'
import { CreateShallowInstance, TGetDependency } from 'shallow-instance';
enum Deps {
DependencyA,
DependencyB,
}
describe('an easier way to instantiate my class', () => {
let service: ServiceToTest;
let dependencies: TGetDependency<typeof ServiceToTest>
beforeEach(() => {
const { serviceInstance, getDependency } = CreateShallowInstance(ServiceToTest, DEPS);
service = serviceInstance;
dependencies = getDependency;
dependencies(DEPS.DEP_A).methodA = jest.fn().mockReturnValue(5);
});
it('should work flawlessly', () => {
dependencies(DEPS.DEP_B).methodB = jest.fn();
service.methodToTest();
expect(dependecies(DEPS.DEP_B).methodB).toBeCalledWith(5)
})
})
Passing Default Mocks
If you want, you can provide your mocks in the moment that CreateShallowInstance is called:
const premadeMocks: TDefaultMocks<typeof ServiceToTest, DEPS> = {
[DEPS.DEP_A]: {
methodA: () => 999
}
}
const {
serviceInstance,
getDependency
} = CreateShallowInstance(ServiceToTest, DEPS, premadeMocks);