canjs / can-util

Essential utilities used by lots of CanJS's projects.
https://canjs.com/doc/can-util.html
MIT License
10 stars 8 forks source link

create Mock Helper #240

Closed christopherjbaker closed 7 years ago

christopherjbaker commented 7 years ago

I've noticed a fair amount of code along the lines of:

var oldWarn = canDev.warn;
var count = 0;
var messages = [
  'Arguments to dispatch should be an array, not multiple arguments.',
  'Arguments to dispatch should be an array.'
];
canDev.warn = function(message) {
  if (count >= messages.length) {
    ok(false, 'canDev.warn called too many times.');
  }
  equal(message, messages[count++], 'warn ' + count);
};

// run tests

canDev.warn = oldWarn;
if (count < messages.length) {
  ok(false, 'canDev.warn not called enough times');
}

I would propose that we create a helper, to enable this functionality, rather than repeating the above code (with other checks, too) repeatedly. Perhaps a syntax similar to this?

var canMock = require('can-util/js/mock');
var mocked = canMock(canDev, 'warn', [
    [ 'Arguments to dispatch should be an array, not multiple arguments.' ],
    'Arguments to dispatch should be an array.'
]);

// run tests

mocked.restore();

(probably support both arrays and single values in the list)

Thoughts? Uses cases that the above won't (but should) meet? Terrible idea?

justinbmeyer commented 7 years ago

looks good to me.

andrejewski commented 7 years ago

I made a mock helper: https://github.com/canjs/can-dom-mutate/blob/303cfe7ed9a1609690b15c36058b94cd18c55a27/test/test-utils.js#L31; may be more flexible to many use cases but also cannot eliminate much boilerplate.

christopherjbaker commented 7 years ago

Closing for canjs/can-test-helpers