0

Mocking normal functions of objects works usually like this:

objToMock.funcToMock = function (param1, ...) {
    equal(param1, 'expectedValue', 'param1 passed correctly');
}

If I try this with a native string function, an error wis thrown:

var name = 'test_string';
name.split = function (limiter) {
    ok(true, 'split called');
}

error:

Source: TypeError: Cannot create property 'split' on string 'test_string'

Is there a blocking mechanism for built-in string functions? I thought strings are also objects with functions. Accessing the prototype of 'test_string' does not work, as 'prototype' is undefined.

Searching the web/stackoverflow is quite hard as "javascript", "string", "split" and "mock" are too generic search values.

Thanks for your help!

Markus Anetz
  • 80
  • 1
  • 8
  • hint: the `prototype` is defined on the `constructor`, not on the `instance`. and take a look at this: `var name = Object('test_string')` – Thomas Apr 21 '16 at 07:54

1 Answers1

0

In fact, the string literal is an independent type, it's different from Object. In javascript, you can only assign an value for key to an Object.

When you call 'string'.split, the string will be transformed to String Object in the behind. So, your assign is useless.

If you've declared your code in strict mode, the assignment will cause your error.

You may change your code like this:

var name = new String('test_string');
name.split = function (limiter) {
    ok(true, 'split called');
}
任劲松
  • 12
  • 2
  • Thank you! It works for me, too. There was a follow up issue as the main method for the unit-test checks provided name-input with "typeof" which does not work with the String object. A doublecheck with "(typeof name === 'string' || name instanceof String)" did the trick. – Markus Anetz Apr 21 '16 at 08:45
  • But, `new String('test_string')` and `'test_string'` will give you the same string... how does this help? – evolutionxbox Apr 21 '16 at 09:25
  • @evolutionxbox In Javascript, string and string object is different, you can use Object.prototype.toString.call to print their real type. – 任劲松 Apr 21 '16 at 09:28
  • @任劲松 that may be true, but the outcome is still the same: http://stackoverflow.com/a/17256340/989920 – evolutionxbox Apr 21 '16 at 09:40