Stub out module function

后端 未结 4 1230
粉色の甜心
粉色の甜心 2021-02-13 21:07

Edit: Being a little bit more precise.

I want to test usecases for a Github API wrapper extension, that our team has created. For testing, we don\'t want to use API wrap

4条回答
  •  不要未来只要你来
    2021-02-13 21:43

    There might be a way to accomplish this in pure Sinon, but I suspect it would be pretty hacky. However, proxyquire is a node library that is designed for solving these sort of issues.

    Supposing you want to test some module foo that makes use of the github module; you'd write something like:

    var proxyquire = require("proxyquire");
    var foo = proxyquire(".foo", {"./github", myFakeGithubStub});
    

    where myFakeGithubStub can be anything; a complete stub, or the actual implementation with a few tweaks, etc.

    If, in the above example, myFakeGithubStub has a property "@global" set as true, (i.e. by executing myFakeGithubStub["@global"] = true) then the github module will be replaced with the stub not only in the foo module itself, but in any module that the foo module requires. However, as stated in the proxyquire documentation on the global option, generally speaking this feature is a sign of poorly designed unit tests and should be avoided.

提交回复
热议问题