feat(jest-when): types for jest-when at https://github.com/timkindberg/jest-when (#28773)

This commit is contained in:
aldentaylor
2018-09-14 09:48:11 -07:00
committed by Ryan Cavanaugh
parent b49e87cd19
commit 8f134e436f
4 changed files with 103 additions and 0 deletions
+22
View File
@@ -0,0 +1,22 @@
// Type definitions for jest-when 1.1
// Project: https://github.com/timkindberg/jest-when#readme
// Definitions by: Alden Taylor <https://github.com/aldentaylor>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="jest" />
export interface PartialMockInstance<T> {
mockReturnValue: jest.MockInstance<T>['mockReturnValue'];
}
export interface When {
<T>(fn: jest.Mocked<T> | jest.Mock<T>): When;
// due to no-unnecessary-generics lint rule, the generics have been replaced with 'any'
// calledWith<T>(...matchers: any[]): PartialMockInstance<T>;
// expectCalledWith<T>(...matchers: any[]): PartialMockInstance<T>;
calledWith(...matchers: any[]): PartialMockInstance<any>;
expectCalledWith(...matchers: any[]): PartialMockInstance<any>;
}
export const when: When;
+57
View File
@@ -0,0 +1,57 @@
import { when } from 'jest-when';
describe('mock-when test', () => {
it('basic usage:', () => {
const fn = jest.fn();
when(fn).calledWith(1).mockReturnValue('yay!');
const result = fn(1);
expect(result).toEqual('yay!');
});
it('Supports multiple args:', () => {
const fn = jest.fn();
when(fn).calledWith(1, true, 'foo').mockReturnValue('yay!');
const result = fn(1, true, 'foo');
expect(result).toEqual('yay!');
});
it('Supports jest matchers:', () => {
const fn = jest.fn();
when(fn).calledWith(
expect.anything(),
expect.any(Number),
expect.arrayContaining([false])
).mockReturnValue('yay!');
const result = fn('whatever', 100, [true, false]);
expect(result).toEqual('yay!');
});
it('Supports compound declarations:', () => {
const fn = jest.fn();
when(fn).calledWith(1).mockReturnValue('no');
when(fn).calledWith(2).mockReturnValue('way?');
when(fn).calledWith(3).mockReturnValue('yes');
when(fn).calledWith(4).mockReturnValue('way!');
expect(fn(1)).toEqual('no');
expect(fn(2)).toEqual('way?');
expect(fn(3)).toEqual('yes');
expect(fn(4)).toEqual('way!');
expect(fn(5)).toEqual(undefined);
});
it('Assert the args:', () => {
const fn = jest.fn();
when(fn).expectCalledWith(1).mockReturnValue('x');
let testPassed = false;
try {
fn(2); // Will throw a helpful jest assertion error with args diff
} catch (e) {
testPassed = true;
}
expect(testPassed).toBeTruthy();
});
});
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"jest-when-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }