Search code examples
javascriptsinon

Using spy and Sinon.js


I have the following function

function trim(value) {
  if (typeof value === 'string') {
    if (String.prototype.trim) {
      value = value.trim();
    } else {
      value = value.replace(/^\s+|\s+$/g, '');
    }

    return value;
  }
} 

I am writing a unit test for it to ensure that when trim is called native String.prototype.trim is called if available. I am trying to use spy to ensure that it is called

var Util = require('test/util/methods');

it('should use native trim', function() {
    var spy = sinon.spy(String.prototype, 'trim');
    Util.trim('test string   ');
    expect(spy.calledOnce).toEqual(true);
    expect(Util.trim('test string    ')).toEqual('test string');
    spy.restore();
  });

But what I feel I should be doing is that when trim is called I should be checking that String.prototype.trim is called also.

How would I go about doing that?


Solution

  • So call trim only once, and then have your two expects:

    it('should use native trim', function() {
        var spy = sinon.spy(String.prototype, 'trim');
        expect(Util.trim('test string    ')).toEqual('test string');
        expect(spy.calledOnce).toEqual(true);
        spy.restore();
    });