Testing this code can be done in two ways:
// Method 1
assert.equal(app.name, 'abc')
assert.equal(app.init(), 'test')
// Method 2
var appInstance = new app()
assert.equal(appInstance.name, 'abc')
assert.equal(appInstance.init(), 'test')
It's important to note that in "Method 2," the variable app should be in uppercase (as is the convention for Constructors).
Testing might be more complex with "Method 1" since var app
needs to be exported as a global variable, making it difficult to test against a mutable global object (which can lead to side-effects).
Therefore, I suggest using "Method 2" as it allows for a clean test setup by re-instantiating the constructor in a beforeEach
block (especially when using a testing framework like Mocha):
describe('the app'', function() {
var app
beforeEach(function() {
app = new App()
})
it(...)
it(...)
})
If you prefer not to use prototypes, you can achieve the same level of testability using the following approach:
var createApp = function() {
var app = {};
app.name = "abc"
app.init = function () {
return "test";
};
return app;
}