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!");
});
});
Related
I have the following code:
var tableRequiredList = [];
var requireListPath = [
'./slimShady.js',
'./chickaChicka.js'
];
var getRequires = function() {
for (var i = 0; i < requireListPath.length; i++) {
((requireNamePath) => {
try {
console.log("INSIDE LOOP RESULT", i, require(requireNamePath)().getName()); // Outputs correct result for the index ("ChickaChicka")
tableRequiredList.push({ "name": requireNamePath, "theReq": require(requireNamePath)() });
// tableRequiredList.push({ "name": requireNamePath, "theReq": ((thePath) => { return require(thePath)(); })(requireNamePath) }); // This also doesn't seem to work.
} catch(err) {
console.log("Error importing: ", requireNamePath, " Error reported: ", err);
}
})(requireListPath[i]);
};
console.log("NAME", tableRequiredList[0].name); // Outputs the correct result ("slimShady.js")
console.log("FUNC NAME", tableRequiredList[0].theReq.getName()); // Always outputs the last item in requireListPath list ("ChickaChicka")
};
getRequires();
Example Module 1 - slimShady.js
((module) => {
module.exports = {};
var exampleModuleName1 = function() {
this.getName = function() {
return 'myNameIsSlimShady';
};
return this;
};
module.exports = exampleModuleName1;
})(module);
Example Module 2 - chickaChicka.js
((module) => {
module.exports = {};
var exampleModuleName2 = function() {
this.getName = function() {
return 'ChickaChicka';
};
return this;
};
module.exports = exampleModuleName2;
})(module);
Why does it output:
INSIDE LOOP RESULT 0 myNameIsSlimShady
INSIDE LOOP RESULT 1 ChickaChicka
NAME ./slimShady.js
FUNC NAME ChickaChicka
When it should be outputting the first index of the tableRequiredList array? This seems to only happen with require(). I have tried using map and forEach, along with the closure example above. All have the same results.
Thanks to #liliscent, I figured it out.
Just needed to change modules to this:
((module) => {
module.exports = {};
var exampleModuleName2 = function() {
var retr = {};
retr.getName = function() {
return 'ChickaChicka';
};
return retr;
};
module.exports = exampleModuleName2;
})(module);
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!'
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")();
I'm looking to lower my overhead on code like this
foo(bar(baz("hello"))) // function hell
ideally something like this
var fbb = bind(foo, bar, baz)
foo("hello")
Does this exist? Native or library?
I looked through underscore and bind.
Underscore has the compose function which will do what you want:
var composite = _.compose(foo, bar, baz);
composite('hello');
function foo(a1){
return 'foo' + a1;
}
function bar(a2){
return 'bar' + a2;
}
function baz(a3){
return 'baz' + a3;
}
alert(foo(bar(baz("hello"))));
var composite = _.compose(foo, bar, baz);
alert( composite('hello') );
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
function getCaller(first) {
var rest = Array.prototype.slice.call(arguments, 1);
return function (value) {
return rest.reduce(function (previous, next) {
return next(previous);
}, first(value));
};
}
function foo(string) {
return string + ' world!';
}
function bar(string) {
return string + ' Hi';
}
function baz(string) {
return string + ' Mom!';
}
var caller = getCaller(foo, bar, baz);
console.log(caller('Hello'));
// Prints: Hello world! Hi Mom!
var bind = function() {
var fns = Array.prototype.slice.call(arguments).reverse();
return function(value) {
for (var key in fns) {
var fn = fns[key];
console.log(fn);
value = fn(value);
}
return value;
}
}
function plusTomato(value) {
return value + "tomato";
}
function plusPear(value) {
return value + "pear";
}
var plus = bind(plusTomato, plusPear);
var y = plus("pancake"); //pankaketomatopear
console.log(y);
var x = plusTomato(plusPear("pancake")); //pankaketomatopear
console.log(x);
I've been toying around with Screeps for a while now and last night I decided to work out some of my behaviors into a class hierarchy by deriving two classes, Miner and Transporter from a Creep main class. However, whenever I do
console.log(_.functions(minerInstance));
I get the exact same function list as when I do
console.log(_.functions(transporterInstance));
Could someone tell me if I'm doing something wrong OR if I'm actually running into a limitation of the environment my code runs in?
This is my code:
////////////////////////////
// Creep.js
var Creep = function(creep, room) {
this.creep = creep;
this.room = room;
this.name = creep.name;
this.id = creep.id;
};
module.exports = Creep;
Creep.prototype = {
tick: function() {
console.log("Base class implementation of tick(), should never happen.");
},
getRole: function() {
return this.creep.memory.role;
}
};
////////////////////////////
// Miner.js
var Creep = require("Creep");
var Miner = function(creep, room) {
this.base = Creep;
this.base(creep, room);
//Creep.call(this, creep, room);
};
module.exports = Miner;
Miner.prototype = Creep.prototype;
Miner.prototype.tick = function() {
var creep = this.creep;
if (creep.memory.activity === undefined || creep.memory.activity === "") {
var target = creep.pos.findNearest(Game.SOURCES_ACTIVE);
this.mine(creep, target);
}
var act = creep.memory.activity;
if (act == "mine") {
var target = this.getTarget(creep);
if (target !== undefined) {
if (creep.energy < creep.energyCapacity) {
creep.moveTo(target);
creep.harvest(target);
} else {
console.log("Write dump to truck code");
/*var trucks = find.transporterInRange(creep, 1);
if (trucks.length) {
creep.moveTo(trucks[0]);
var amount = trucks[0].energyCapacity - trucks[0].energy;
creep.transferEnergy(trucks[0], amount);
}*/
}
}
}
};
Miner.prototype.mine = function(creep, target) {
creep.memory.target = target.id;
creep.memory.activity = "mine";
};
Miner.prototype.getTarget = function(creep) {
return Game.getObjectById(creep.memory.target);
};
////////////////////////////
// Transporter.js
var Creep = require("Creep");
var Transporter = function(creep, room) {
Creep.call(this, creep, room);
};
module.exports = Transporter;
Transporter.prototype = Creep.prototype;
Transporter.prototype.tick = function() {
var creep = this.creep;
if (creep.energy < creep.energyCapacity) {
var miner = this.room.findByRole(creep, "miner");
console.log(miner);
if (miner !== null) {
//console.log(miner[0].name);
//creep.moveTo(miner);
} else
console.log("no miners found");
} else {
console.log("moving to drop");
//var drop = find.nearestEnergyDropOff(creep);
//creep.moveTo(drop);
//creep.transferEnergy(drop);
}
};
With this line...
Miner.prototype = Creep.prototype;
... you tell JS that both prototypes are actually the same object. Hence any update for Miner.prototype will affect Creep.prototype too.
One possible approach is using Object.create when establishing the link between prototypes. Here goes a simplified example:
function Foo(a) {
this.a = a;
}
Foo.prototype.tick = function() { console.log('Foo ticks'); };
Foo.prototype.tock = function() { console.log('Foo tocks'); };
function Bar(a, b) {
this.base = Foo;
this.base(a);
this.b = b;
}
Bar.prototype = Object.create(Foo.prototype);
// as you inherit all the properties, you'll have to reassign a constructor
Bar.prototype.constructor = Bar;
Bar.prototype.tick = function() { console.log('Bar ticks'); };
var f = new Foo(1);
f.tick(); // Foo ticks
f.tock(); // Foo tocks
console.log(f); // Foo { a=1, ... }
var b = new Bar(1, 2);
b.tick(); // Bar ticks
b.tock(); // Foo tocks
console.log(b); // Bar { a=1, b=2, ... }