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!
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');
}