I'm creating unit tests using Qunit. I want to test that, for a non-fatal error, a warning message is sent to console. (Yes, I know we shouldn't be writing to console in production code. Let it go.)
So, I've got this popup utility that accepts a config object:
popup.js:
showPopup = function(cfg){
if !(cfg.message){
utils.log('A message is required!');
}
};
(utils.log function will handle whether or not the browser actually supports console)
And then my tests file does its thing.
popup.tests.js:
showPopup({stuff: 'stuff', message: 'I am a popup!'});
QUnit.test('A warning message is logged to console', function (assert) {
// want to know a message was sent
}
How can I confirm that the message was sent?
What I would do is override console.log in your unit test:
window.console = (function(old_logger) {
var previous_message;
var log = function(msg) {
previous_message = msg;
old_logger.log(msg);
}
var previous = function() {
return previous_message;
}
return { log: log, previous: previous }
})(window.console);
And then you can do:
showPopup({stuff: 'stuff'});
assert.equal('A message is required!', console.previous());
显然,对我们来说“正确”的答案是使用sinon stub。
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.