How do I stub node.js built-in fs during testing?

前端 未结 11 2112
暖寄归人
暖寄归人 2021-02-05 02:21

I want to stub node.js built-ins like fs so that I don\'t actually make any system level file calls. The only thing I can think to do is to pass in fs

11条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-05 03:00

    Here's how i think of this:

    The way you do it is the obvious first step but it sucks having to pass those things in everywhere— Callers of your functions shouldn't care that you want to test with mocks. You don't want to just overwrite or monkey-patch the global modules in the global namespace for your test. And the normal dependency injection model is pretty verbose in Javascript since there's no class-local scope.

    So around the whole module, I've done like (function(fs, net, http) { … })(fs, net, http);

    Then inside the module, if there's a class constructor, make the mocks optional extra parameters to the constructor (or possible properties of a single mocks object parameter or something) and your test passes in the mocks. Your constructor overwrites the real node modules within only the module's local scope.

    Alternately if the module just has static functions; have one such function which initializes the mocks, you can validate that that function is not called in your prod code.

提交回复
热议问题