Test that a function calls another function in an ES6 module with Sinon.js

前端 未结 1 442
感情败类
感情败类 2020-12-16 01:48

I want to test that a function in an ES6 module calls another function using Sinon.js. Here\'s the basic layout of what I\'m doing:

foo.js

export fun         


        
相关标签:
1条回答
  • 2020-12-16 02:17

    You're right in thinking this isn't possible with the way the module is currently structured.

    When the code is executed, the baz reference inside function bar is resolved against the local implementation. You can't modify that since outside of the module code there's no access to the internals.

    You do have access to exported properties, but you can't mutate these and so you can't affect the module.

    One way to change that is using code like this:

    let obj = {};
    obj.bar = function () {
     this.baz();
    }
    
    obj.baz = function() {
     ...
    }
    
    export default obj;
    

    Now if you override baz in the imported object you will affect the internals of bar.

    Having said that, that feels pretty clunky. Other methods of controlling behaviors exist such as dependency injection.

    Also, you should consider whether or not you actually care if baz was called. In standard "black-box testing", you don't care how something is done, you only care what side effects it generated. For that, test if the side effects you expected happened and that nothing else was done.

    0 讨论(0)
提交回复
热议问题