jest-decorated
jest-decorated copied to clipboard
Decorators library for writing jest-based tests
Decorators library for writing jest-based tests
Wrapper around jest JavaScript testing framework.
Provides decorators with core jest globals. Also, provides utilities to minimize boilerplate code and make tests code more consistent.
Jest test:
describe("MyFnSpec", () => {
const consoleLogSpy = jest.spyOn(console, "log");
afterEach(() => {
consoleLogSpy.mockClear();
});
afterAll(() => {
consoleLogSpy.mockRestore();
});
test("shouldCallLogTwice", () => {
myFn("foo");
expect(consoleLogSpy).toHaveBeenCalledTimes(2);
});
test("shouldCallLogOnce", () => {
myFn("bar");
expect(consoleLogSpy).toHaveBeenCalledTimes(1);
});
});
Same test with @jest-decorated
:
@Describe()
class MyFnSpec {
@Spy(console, "log")
consoleLogSpy;
@Test()
shouldCallLogTwice() {
myFn("foo");
expect(this.consoleLogSpy).toHaveBeenCalledTimes(2);
}
@Test()
shouldCallLogOnce() {
myFn("bar");
expect(this.consoleLogSpy).toHaveBeenCalledTimes(1);
}
}
Install
Does not bring jest
as a dependency, you should install the wanted version by yourself.
Install jest
npm i -D jest
Install @jest-decorated
npm i -D @jest-decorated/core
Install extensions (if needed)
npm i -D @jest-decorated/react
Setup
With setupFilesAfterEnv
jest option
You can register decorators once and use them everywhere, without importing! To achieve that, add globals
files to setupFilesAfterEnv
jest config.
For example, if we want to register core
and react
decorators globally:
{
"setupFilesAfterEnv": [
"@jest-decorated/core/globals",
"@jest-decorated/react/globals"
]
}
Or, if you already have single entry point for tests setup:
{
"setupFilesAfterEnv": [
"<rootDir>/testSetup.ts"
]
}
// testSetup.ts
import "@jest-decorated/core/globals";
import "@jest-decorated/react/globals";
With importing globals
file
Another option is to import globals
files in each test separately:
// myFn.spec.ts
import "@jest-decorated/core/globals";
import "@jest-decorated/react/globals";
@Describe()
@RunWith(ReactTestRunner)
class MyFnSpec {
// ...
}
With direct import
If solutions above doesn't serves your needs, you can use direct import:
// myFn.spec.ts
import { Describe, RunWith } from "@jest-decorated/core";
import { ReactTestRunner } from "@jest-decorated/react";
@Describe()
@RunWith(ReactTestRunner)
class MyFnSpec {
// ...
}
TypeScript
When using with TypeScript, make sure your setup file (in setupFilesAfterEnv
section) is a .ts
and not a .js
to include the necessary types.
You will also need to include your setup file and the test folder in your tsconfig.json
if you haven't already:
{
"include": [
"./testSetup.ts",
"./__tests__"
]
}
Extensions
Support for different libs and frameworks. Currently, only React is strongly supported.
Decorators
Read docs.
Contributing
Contribution guidelines for this project
License
MIT License