In my main.js, I have:
var example = require('./test');
example.speak('Hello world');
While in my test.js, I have:
module.exports = function() {
this.speak = function(str) {
str += ' < you typed.';
return str;
};
this.listen = function(str) {
return str;
};
};
What exactly am I doing wrong so that I can use browserify correctly with this?
You should either export an object:
module.exports = {
speak: function () {},
// etc
}
or use
var example = new require("./test")();
Related
This is my basic JS to concatenate two strings, the context.getVariable is something which I want to mock using Sinon,
//util.js
var p;
function concat(p) {
var first_name = context.getVariable('first_name');
var res = p.concat(first_name);
return res;
}
concat(p);
I have added this test.js,
var expect = require('expect.js');
var sinon = require('sinon');
var rewire = require('rewire');
var app = rewire('./util.js');
var fakeContext = {
getVariable: function(s) {}
}
var contextGetVariableMethod;
beforeEach(function () {
contextGetVariableMethod = sinon.stub(fakeContext, 'getVariable');
});
afterEach(function() {
contextGetVariableMethod.restore();
});
describe('feature: concat', function() {
it('should concat two strings', function() {
contextGetVariableMethod.withArgs('first_name').returns("SS");
app.__set__('context', fakeContext);
var concat = app.__get__('concat');
expect(concat("988")).to.equal("988SS");
});
});
I am running,
node_modules.bin> mocha R:\abc\js-unit-test\test.js
util.js:7
var first_name = context.getVariable('first_name');
^
TypeError: context.getVariable is not a function
You need to import actual context here and then use sinon.stub to mock that getVariable method so it it will get that method when your actual code is running.
var expect = require('expect.js');
var sinon = require('sinon');
var rewire = require('rewire');
var context = require('context') // give correct path here
var app = rewire('./util.js');
var fakeContext = {
getVariable: function(s) {}
}
beforeEach(function () {
contextGetVariableMethod = sinon.stub(context, 'getVariable');
});
afterEach(function() {
contextGetVariableMethod.restore();
});
describe('feature: concat', function() {
it('should concat two strings', function() {
contextGetVariableMethod.withArgs('first_name').returns("SS");
var concat = app.__get__('concat');
expect(concat("988")).to.equal("988SS");
});
});
As I am new to javascript, and i got a code which explains how module can be created and used but I have problem in figuring out what does the for loop does in the following snippet, So can anybody help me out
in figuring out how the code is working.
var MyModules = (function Manager() {
var modules = {};
function define(name, deps, impl) {
for (var i=0; i<deps.length; i++) {
deps[i] = modules[deps[i]];
}
modules[name] = impl.apply( impl, deps );
}
function get(name) {
return modules[name];
}
return {
define: define,
get: get
};
})();
MyModules.define( "bar", [], function(){
function hello(who) {
return "Let me introduce: " + who;
}
return {
hello: hello
};
} );
MyModules.define( "foo", ["bar"], function(bar){
var hungry = "hippo";
function awesome() {
console.log( bar.hello( hungry ).toUpperCase() );
}
return {
awesome: awesome
};
} );
var bar = MyModules.get( "bar" );
var foo = MyModules.get( "foo" );
console.log(
bar.hello( "hippo" )
);
You can read good article explain what are module how you can implement it.
https://medium.freecodecamp.org/javascript-modules-a-beginner-s-guide-783f7d7a5fcc
function myModule() {
this.hello = function() {
return 'hello!';
}
this.goodbye = function() {
return 'goodbye!';
}
}
module.exports = myModule;
You can you use the above module shown below
var myModule = require('myModule');
var myModuleInstance = new myModule();
myModuleInstance.hello(); // 'hello!'
myModuleInstance.goodbye(); // 'goodbye!'
I can't get toBeCalled() working in my Jade test script.
I get the following error msg when run the Jade test:
Error: toBeCalled() should be used on a mock function or a jasmine spy
I have a call to jest.unmock('../fooey') so not sure why I'm getting the error ?
fooey.js
var foo = function(phrase) {
return bar(phrase);
}
var bar = function(greeting) {
console.log(greeting + " Watz up?");
}
foo("Hi Bob!");
module.exports.foo = foo;
module.exports.bar = bar;
fooey-test.js:
jest.unmock('../fooey'); // unmock to use the actual implementation.
describe('fooey()', () => {
const foo = require('../fooey').foo;
const bar = require('../fooey').bar;
it('bar() is called.', () => {
foo("Hi Bob!");
expect(bar).toBeCalled();
});
});
I got it working with both a mock of bar() and also using spyOn()...
fooey.js
var Fooey = function() {
// var self = this;
this.foo = function(phrase) {
// var result = self.bar(phrase);
var result = this.bar(phrase);
return result;
// return "Junky."
};
this.bar = function(greeting) {
var result = greeting + " Watz up?"
console.log(result);
return result;
};
};
module.exports = Fooey;
fooey-test.js
jest.unmock('../fooey'); // unmock to use the actual implementation.
describe('fooey()', () => {
const Fooey = require('../fooey');
const fooey = new Fooey();
it('mock: bar() is called.', () => {
var myFooey = {
foo: fooey.foo,
bar: jest.genMockFunction()
};
myFooey.foo("Hello");
expect(myFooey.bar).toBeCalledWith("Hello");
});
it('bar() is called with "Hi Bob!".', () => {
spyOn(fooey, 'bar');
fooey.foo("Hi Bob!");
expect(fooey.bar).toHaveBeenCalledWith("Hi Bob!");
});
});
Completely loosing my mind on this:
I have an express app:
here is a snapshot of a few files for this example:
app.js
-models
--Event.js
--Match.js
routes
--matches.js
app.js:
global.__base = __dirname + '/';
var MatchModel = require('./models/Match');
var EventModel = require('./models/Event');
//...
matches.js:
var EventModel = require(__base + 'models/Event');
var MatchModel = require('../models/Match.js')
router.get('/', [passport.authenticate('bearer', {session: false}), function (req, res) {
EventModel.something()
}])
Event.js:
var MatchModel = require(__base + 'models/Match')
function something() {
MatchModel.createQuery()
return "jizz"
}
module.exports = {
createQuery : createQuery,
}
Match.js:
function createQuery() {
//..
}
module.exports = {
createQuery:createQuery
}
when the GET matches/ API is called:
Inside Event.js, MatchModel.createQuery() gives the error MatchModel.createQuery() is not a function. but if I move var MatchModel = require(__base + 'models/Match') inside the something() function, it works.
You can create a primary function createQuery and define its prototypes as per requirements and then export that function to be used in you Event.js
Inside Event.js
var matchModel = require(./Match.js)
exports.getSometing = function(){
var testSomething = new matchModel();
var resultOfCreateQuery = testSomething.createQuery()
console.log('Result of createQuery : '+resultOfCreateQuery);
}
Inside Match.js
function something(){
//another logic
}
something.prototype.createQuery= function(){
//create query logic
return "jizz"
}
module.exports = something;
I hope this helps :)
You will have to require them and append ()
Event.js:
var MatchModel = require(__base + 'models/Match')()
function EventModel () {
function something() {
MatchModel.createQuery()
return "jizz"
}
}
module.exports = EventModel
Match.js:
function MatchModel () {
function createQuery () {
//Do Something
}
}
module.exports = MatchModel
See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype
I have the following problem:
A ASP.NET MVC3 application, and in _Layout.cshtml, in header section, I have referenced several javascript scripts, as follows:
<script src="#Url.Content("~/Scripts/app/app.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/app/listEnveloppe.js")" type="text/javascript"></script>
In app.js I have defined App object as follows:
var App = {
init: function () {
if (window.console == undefined) {
window.console = {
log: function () {
var str = '';
for (var i in arguments[0]) {
str += i + ':\t' + arguments[0][i] + '\n';
}
alert(str);
}
};
}
/* ....*/
}
Then App object is referenced in listEnveloppe.js as below
App.listEnveloppe = new Function;
The problem is, this code works on FF and Chrome, but not in IE8
Does anyone knows what can be wrong?
Thank you
Maybe a lack of parenthesis in the Function constructor?
App.listEnveloppe = new Function(); // <----- missing () ?
As that wasn't the case, try declaring (and referring to) App as a property of window. And do it in an agnostic way relative to the order of declaration of the scripts:
// In app.js:
var appInstance = window.App || {};
appInstance.init = function () {
};
// In listEnveloppe.js:
var appInstance = window.App || {};
appInstance.listEnveloppe = new Function();
You have some unclosed parenthesis. Try fixing your javascript:
var App = {
init: function () {
if (window.console == undefined) {
window.console = {
log: function () {
var str = '';
for (var i in arguments[0]) {
str += i + ':\t' + arguments[0][i] + '\n';
}
alert(str);
}
};
}
}
/* ....*/
};