nestjs-jester v0.0.1
Installation
π‘ Install jest-mock-extended
as a peer dependency
With NPM:
npm i -D nestjs-jester jest-mock-extended
Or with Yarn:
yarn add -D nestjs-jester jest-mock-extended
Motivation πͺ
Unit tests exercise very small parts of the application in complete isolation. \ "Complete isolation" means that, when unit testing, you donβt typically connect your application with external dependencies such as databases, the filesystem, or HTTP services. That allows unit tests to be fast and more stable since they wonβt fail due to problems with those external services. (Thank you, Testim.io - jump to source)
This package helps isolate the dependencies of an Injectable
class, by using a simple
reflection mechanism (with NestJS Refelector
). When used in conjunction with
jest-mock-extended
library, all the class (Injectable
) dependencies will be overridden
automatically and become mocks (or deep mocks if you want it to).
Example and Usage πβ
@Injectable()
export class SomeService {
public constructor(
private readonly logger: Logger,
private readonly catsService: CatsService,
private readonly userService: UserService,
private readonly featureFlagService: FeatureFlagService,
) {}
public async doSomethingNice() {
if (this.featureFlagService.isFeatureOn()) {
const users = await this.userService.getUsers('https://example.com/json.json');
this.logger.log(users);
return users;
}
return null;
}
}
import { DeepMockOf, MockOf, Spec } from 'nestjs-jester';
describe('SomeService Unit Test', () => {
let someService: SomeService;
let logger: MockOf<Logger>;
let userService: MockOf<UserService>;
const USERS_DATA = [{ name: 'user', email: 'user@user.com' }];
beforeAll(() => {
const { unit, unitRef } = Spec.createUnit<SomeService>(SomeService)
.mock(FeatureFlagService)
.using({
isFeatureOn: () => Promise.resolve(true),
})
// All the rest of the dependencies will be mocked
// Pass true if you want to deep mock all of the rest
.compile();
someService = unit;
userService = unitRef.get(UserService);
});
describe('When something happens', () => {
beforeAll(() => (userService.getUsers.mockResolvedValueOnce(USERS_DATA));
test('then check something', async () => {
const result = await service.doSomethingNice();
expect(logger.log).toHaveBeenCalledWith(USERS_DATA);
expect(result).toEqual(USERS_DATA);
});
});
});
Still need further example? Jump to full sample π
More about jest-mock-extended
package π¦
jest-mock-extended
is a library which enables type safe mocking for Jest with TypeScript.
It provides a complete Typescript type safety for interfaces, argument types and return types
and has the ability to mock any interface or object.
License π
Distributed under the MIT License. See LICENSE
for more information.