如何在测试中spyOn或模拟函数声明/表达式?

时间:2017-11-24 09:18:37

标签: unit-testing jasmine mocking jest

我试图将模块中调用的函数操作为true,但是如果模块没有将函数封装到对象上,我该如何模拟函数的值?

  // app.js
  function start(foo) {
    if (isGood(foo)) initialize(foo)
  }
  function isGood = function(name) {
    return dosomething_really_complicated_here(name) // i dont care about this, and actuallyi want to mock its return value
  }

  function initialize(foo) {
    //... interesting stuff
  }

  // export {
  //  start as default,
  //  initialize
  // }


  // IN ANOTHER FILE
  // app.test.js
  // import app from './app'
  // const { start, initialize } = app

  describe('app', () => {
    beforeEach(() => {
      start('abc')
      // TODO: here I want to stub isGood to return true or false, note i could
      // TODO: i also want to spy on initialize
    })
    
    it('should call initialize', () => {
      expect(initializeSpy).toHaveBeenCalled()
    })
  })
<link href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.8.0/jasmine.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.8.0/jasmine.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.8.0/jasmine-html.js"></script>

1 个答案:

答案 0 :(得分:0)

取决于您自己的想法和偏好

  1. 使用rewirebabel-plugin-rewire加载经过测试的模块 并用间谍取代deps
  2. 使用proxyquiremockery,你几乎可以 像上面一样。
  3. 您可以在测试环境中公开私有功能并排除 它来自生产。请参阅this article
  4. 中的详情