简体   繁体   中英

Mocking/Stubbing globals in sails.js

In Sails.js we've created a wrapper around logging functionality so that security audit logs have the same format and information etc.

I'd like to unit test the wrapper that in turn calls sails.log.info . How can I mock/stub the global sails.log.info and then verify that it was called? I've used proxyquire and rewire before but they were in the context of stubbing out modules that were required into the files.

It's JavaScript so you can simply overwrite it and then return the original method

var originalLogFunction = sails.log.info;
var actualArgs;
sails.log.info = function(arg1, arg2){
    actualArgs = { arg1: arg1, arg2: arg2 };
}

// call your method that you test here

sails.log.info = originalLogFunction;

// assert your actualArgs have the correct args

You can only count the number of times the method was called

You can look into the library MoqJs . It's a mocking library for JavaScript based on the ideas of Moq for C#

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM