Stubbing method in same file using Sinon

后端 未结 3 1600
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-04 09:04

I\'m trying to unit test a function in a file while stubbing another function in the SAME file, but the mock is not being applied and the real method is being called. Here\

3条回答
  •  悲哀的现实
    2021-01-04 09:46

    While the above does work, it's definitely a workaround as my linter was quick to inform.

    I ended up separating modules and using proxyquire. This library allows you to easily substitute any / all exports with those of your choosing, sinon stub spy or mocks included. e.g. :

    in b.js

    export const fnB = () => 'hey there!';
    

    in a.js

    import { fbB } from 'b.js';
    export const fnA = () => fbB();
    

    in a.test.js

    import { noCallThru } from 'proxyquire';
    const proxyquireStrict = noCallThru();
    const stubB = stub().returns('forced result');
    const moduleA = proxyquireStrict('a.js', {
        'b.js' : { fnB: stubB }
    }).fnA; 
    
    console.log(fnA()); // 'forced result'
    

提交回复
热议问题