Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/Typescript-TDD/jest-ts-auto-mock

Jest test utility with automatic mock creation for interfaces and classes
https://github.com/Typescript-TDD/jest-ts-auto-mock

fake jest-mock mock mock-interface mock-typescript testing typescript-transformer

Last synced: 22 days ago
JSON representation

Jest test utility with automatic mock creation for interfaces and classes

Awesome Lists containing this project

README

        

# Jest Ts Auto Mock

[![Actions Status](https://github.com/Typescript-TDD/jest-ts-auto-mock/workflows/Master/badge.svg)](https://github.com/Typescript-TDD/jest-ts-auto-mock/actions)

This is a library that extend [ts-auto-mock](https://github.com/Typescript-TDD/ts-auto-mock/) to be used with jest

The intention of the library is to automatically assign jest mock to functions giving you type safety

## Requirements

typescript@^3.2.2

ts-jest@>=24 <27
## Installation

- A Transformer needs to be provided at compile time.
We need to tell ts-jest to use ttypescript that allow us to use a transformer.
### IMPORTANT:
- set "cacheBetweenTests" as false
- Add the transformer to your ts config
```ts
{
"compilerOptions": {
...
"plugins": [
{ "transform": "ts-auto-mock/transformer", "cacheBetweenTests": false }
]
}
}
```

- Enable ttypescript into the ts-jest configuration
```ts
...
"globals": {
"ts-jest": {
"compiler": "ttypescript"
}
}
```

- provide jest-ts-auto-mock config before your test
```ts
"jest": {
...
"setupFiles": [
"/config.ts"
]
...
},
```

- config file
```ts
import 'jest-ts-auto-mock'

```

## Examples
[ts-jest-ttypesctipt](examples/ts-jest-ttypescript)

## Usage
1) create an interface
```ts
interface Interface {
methodToMock: () => string
}
```
2) create a mock
```ts
const mock: Interface = createMock();
```
3) get the method mock

You can get the method spy in 2 different ways

Through method
```ts
import { On, method } from "ts-auto-mock/extension";
const mockMethod: Jest.Mock = On(mock).get(method(mock => mock.methodToMock));
```

Through string
```ts
import { On, method } from "ts-auto-mock/extension";
const mockMethod: Jest.Mock = On(mock).get(method('methodToMock'));
```
4) trigger the method
```ts
someMethodThatWillTriggerInterfaceA();
expect(mockMethod).toHaveBeenCalled();
```

## Authors

* [**Vittorio Guerriero**](https://github.com/uittorio)
* [**Giulio Caprino**](https://github.com/pmyl)

## License

This project is licensed under the MIT License