Search code examples
javascriptnode.jsmockingmonkeypatchingstubbing

Node.js/JavaScript Stubbing of Built-in Types?


This exercise is fairly academic, but it's useful in understanding JavaScript's behavior.

Why does this work:

var fs = require('fs');
console.log(fs.readdirSync('/').length); //approximately '28' on my Macbook
fs['readdirSync'] = function(){ return ['/tmp', '/bin']; };
console.log(fs.readdirSync('/').length); //'2' as expected

and this doesn't:

var a = "hello world";
console.log(a.length); //'11'
a['length'] = 1000;
console.log(a.length); //still '11'... why??

I know it's possible to monkeypatch JavaScript built-in types such as String, but is it possible to stub them?

Thanks in advance.


Solution

  • Courtesy of TJ Holowaychuk: Strings are immutable. So it seems like it's not possible in this manner.