最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to spy on an imported function using Sinon? - Stack Overflow

programmeradmin8浏览0评论

Let's say we want to test that a specific function is called by another function using Sinon.

fancyModule.js

export const fancyFunc = () => {
  console.log('fancyFunc')
}

export default const fancyDefault = () => {
  console.log('fancyDefault')
  fancyFunc()
}

fancyModule.test.js

import sinon from 'sinon'
import fancyDefault, { fancyFunc } from '../fancyModule'

describe('fancyModule', () => {
  it('calls fancyFunc', () => {
    const spy = sinon.spy(fancyFunc)
    fancyDefault()
    expect(spy.called).to.be.true
  })
})

When I run this test the actual value is always false. Also, the original function fancyFunc() gets invoked (outputs fancyFunc) instead of being mocked.

Let's say we want to test that a specific function is called by another function using Sinon.

fancyModule.js

export const fancyFunc = () => {
  console.log('fancyFunc')
}

export default const fancyDefault = () => {
  console.log('fancyDefault')
  fancyFunc()
}

fancyModule.test.js

import sinon from 'sinon'
import fancyDefault, { fancyFunc } from '../fancyModule'

describe('fancyModule', () => {
  it('calls fancyFunc', () => {
    const spy = sinon.spy(fancyFunc)
    fancyDefault()
    expect(spy.called).to.be.true
  })
})

When I run this test the actual value is always false. Also, the original function fancyFunc() gets invoked (outputs fancyFunc) instead of being mocked.

Share Improve this question edited Jul 16, 2017 at 17:21 Marc asked Jul 14, 2017 at 19:55 MarcMarc 3,0703 gold badges29 silver badges40 bronze badges 2
  • Please show the export statement of "fancyModule.js". – try-catch-finally Commented Jul 16, 2017 at 15:39
  • Thanks, I've updated my question with exports. – Marc Commented Jul 16, 2017 at 17:22
Add a comment  | 

2 Answers 2

Reset to default 11

You can change the import style, and import your module as an Object like this

import sinon from 'sinon'
import * as myModule from '../fancyModule'

describe('fancyModule', () => {
  it('calls fancyFunc', () => {
    const spy = sinon.spy(myModule, 'fancyFunc');
    myModule.fancyDefault()
    expect(spy.called).to.be.true
  })
})

You should use https://github.com/speedskater/babel-plugin-rewire/

import sinon from 'sinon'
import fancyDefault, { __RewireAPI__ } from '../fancyModule'

describe('fancyModule', () => {
  it('calls fancyFunc', () => {
    const spy = sinon.spy()
    __RewireAPI__.__Rewire__('fancyFunc', spy)
    
    fancyDefault()

    expect(spy.called).to.be.true
  })
})

Also, check example: https://github.com/speedskater/babel-plugin-rewire#test-code-2

发布评论

评论列表(0)

  1. 暂无评论