Skip to content

Instantly share code, notes, and snippets.

@ivawzh
Last active July 13, 2020 06:54
Show Gist options
  • Save ivawzh/006fc79e1ed9220d3d80e938ce579632 to your computer and use it in GitHub Desktop.
Save ivawzh/006fc79e1ed9220d3d80e938ce579632 to your computer and use it in GitHub Desktop.
Typescript stub/mock with type check
// 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