Last active
July 13, 2020 06:54
-
-
Save ivawzh/006fc79e1ed9220d3d80e938ce579632 to your computer and use it in GitHub Desktop.
Typescript stub/mock with type check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// at b.ts | |
export class B { | |
public iAm() { | |
return 'B' | |
} | |
} | |
// at a.ts | |
import { B } from './b' | |
const b = new B() | |
export class A { | |
public doIt() { | |
return 'doIt ' + b.iAm() | |
} | |
} | |
// at a.spec.ts | |
jest.mock('../src/b') | |
import { A } from '../src/a' | |
import * as bModule from '../src/b' | |
const a = new A() | |
const { B } = bModule as jest.Mocked<typeof bModule> | |
B.prototype.iAm.mockImplementation(() => 'C') | |
// GREEN | |
describe('a', () => { | |
it('do', () => { | |
expect(a.doIt()).toEqual('doIt C') | |
}) | |
}) | |
// Typecheck will fail | |
B.prototype.iAm.mockImplementation(() => 11) | |
// Type 'number' is not assignable to type 'string'.ts(2322) | |
// index.d.ts(1183, 33): The expected type comes from the return type of this signature. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment