web-dev-qa-db-ja.com

jestで単一インスタンスメソッドのモックを解除する方法

rspecから来たので、冗談でのモックを理解できません。私が試みているアプローチは、クラスのコンストラクターとそのすべての関数をオートモックし、それらを1つずつモック解除して、その1つの関数のみをテストすることです。私が見つけることができる唯一のドキュメントは、2つのクラスを使用し、1つのクラスをモックし、それらの関数が他のモックされていないクラスから呼び出されることをテストすることです。

以下は、私が何をしようとしているのかについての基本的で不自然な考えです。誰かが私をこれを冗談にする方法に導くことができますか?

foo.js

class Foo
  constructor: ->
    this.bar()
    this.baz()
  bar: ->
    return 'bar'
  baz: ->
    return 'baz'

foo_test.js

// require the class
Foo = require('foo')

// mock entire Foo class methods
jest.mock('foo')

// unmock just the bar method
jest.unmock(Foo::bar)

// or by
Foo::bar.mockRestore()

// and should now be able to call
foo = new Foo
foo.bar() // 'bar'
foo.baz() // undefined (still mocked)

// i even tried unmocking the instance
foo = new Foo
jest.unmock(foo.bar)
foo.bar.mockRestore()
6
brewster

mockFn.mockRestore()[email protected]

// Create a spy with a mock
const consoleInfoSpy = jest.spyOn(console, 'info').mockImplementation(() => {})

// Run test or whatever code which uses console.info
console.info('This bypasses the real console.info')

// Restore original console.info
consoleInfoSpy.mockRestore()
1
Nick Ribal