How to test if a function inside function called with right parameter - jestjs

I got this kind of function:
const plus1 = x => x + 1;
const plus2 = x => x + 2;
const returnPlus1OrPlus2 = (number, code) =>
code === 1 ? plus1(number * 3) : plus2(number);
// if the parameter code is 1 then call function plus1 with param number*3,
// if not then just call function plus2 with param number
export default returnPlus1orPlus2;
I have to create a unit testing using jest for that function and I need to test if the function returnPlus1OrPlus2 calls the right function whether plus1 or plus2 based on the parameter code invoked.
test('function returnPlus1OrPlus2 should call function plus1'()=>{
expect(returnPlus1OrPlus2(2, 1)).toBe(7);
//expect(function plus 1 was called with 6)
})
How to mock functions plus1 and plus2 and write something like this in test?
//expect(function plus1 was called with 6)

If you want to mock or spy on the function(plus1, plus2), you need to make sure you can access it. Then, use jest.spyOn add a spy on the function and assert it is to be called or not. Here is the solution:
index.js:
const plus1 = x => x + 1;
const plus2 = x => x + 2;
const returnPlus1OrPlus2 = (number, code) =>
code === 1 ? exports.plus1(number * 3) : exports.plus2(number);
exports.plus1 = plus1;
exports.plus2 = plus2;
export default returnPlus1OrPlus2;
index.spec.js:
import returnPlus1orPlus2 from "./";
const mymath = require("./");
describe("returnPlus1orPlus2", () => {
it("should call plus1", () => {
const plus1Spy = jest.spyOn(mymath, "plus1");
expect(returnPlus1orPlus2(2, 1)).toBe(7);
expect(plus1Spy).toBeCalledWith(6);
});
it("should call plus2", () => {
const plus2Spy = jest.spyOn(mymath, "plus2");
expect(returnPlus1orPlus2(2, 2)).toBe(4);
expect(plus2Spy).toBeCalledWith(2);
});
});
Unit test result with 100% coverage:
PASS src/stackoverflow/59168766/index.spec.js
returnPlus1orPlus2
✓ should call plus1 (5ms)
✓ should call plus2 (1ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.js | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 4.109s, estimated 8s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59168766

Related

fast-xml-parser parsing xml input incorrectly

Why is this test not passing with fastxmlparser
import parser from 'fast-xml-parser'
test("fastxmlparser", () => {
let parsed = parser.parse('<detail><name>john</name><value>116347579610481033</value></detail>')
expect(parsed.detail.value).toBe('116347579610481033')
})
Expected value to be:
"116347579610481033"
Received:
116347579610481040
Difference:
Comparing two different types of values. Expected string but received number.
95 | test("fastxmlparser", () => {
96 | let parsed = parser.parse('<detail><name>john</name><value>116347579610481033</value></detail>')
> 97 | expect(parsed.detail.value).toBe('116347579610481033')
98 | })
99 |
100 |

I get Key Error: "po5" after everything is done

car={"po1":50,"po2":"-","po3":15,"po4":"+","po5":12}
vocar = list(car.keys())
inter=0
def cal(car,vocar,inter):
while len(car)!=1:
for inter in range(len(car)):
if car.get(vocar[inter],0)=="+":
new=car.get(vocar[inter-1])+car.get(vocar[inter+1])
car.pop(vocar[inter])
car.pop(vocar[inter+1])
car.update({vocar[inter-1]:new})
car1=car
vocar1=list(car1.keys())
inter1=0
cal(car1,vocar1,inter1)
elif car.get(vocar[inter],0)=="-":
new=car.get(vocar[inter-1])-car.get(vocar[inter+1])
car.pop(vocar[inter])
car.pop(vocar[inter+1])
car.update({vocar[inter-1]:new})
car1=car
vocar1=list(car1.keys())
inter1=0
cal(car1,vocar1,inter1)
print(car)
cal(car,vocar,inter)
I keep getting a key error even if I get what I wanted, which is {'po1': 47}.
But after everything is done, it gives me a key error. Please help!
At first:
while len(car)!=1
You pop item from car and try to make a recursion function then you can use:
if not car:
return
for inter in range(len(car)):
# ....
When you make a loop like this:
for inter in range(len(car))
that means:
| loop | inter |
|:----:|:-----:|
| 1 | 0 | car => [X, X, X ,X ,X]
| 2 | 1 | car => [X, X, X ,X]
| 3 | 2 | car => [X, X, X] ! ERR !
| 4 | 3 |
| 5 | 4 |
in loop 3 you have an error (maybe ;))
you can use the main dict:
for inter in car:
According above, You didn't need vocar anymore:
if car.get(inter,0)=="+":
"po1" is str and "po2" is int then you can't use + operator between int and int.
dictionaries are unordered
That means, every time you run it, item arrangments may be changed! so I change it:
car = [("po1",50), ("po2","-"),("po3",15),("po4","+"),("po5",12)]
We changed car then we can do this:
if inter[1] == "+":
car[head-1] = (inter[0], car[head-1][1]+car[head+1][1])
finally, we MUST remove car[head+1] at first and then remove car[inter].
car = [("po1",50), ("po2","-"),("po3",15),("po4","+"),("po5",12)]
def cal(car):
head = 0
if not car:
return
for inter in car:
if inter[1] == "+":
car[head-1] = (inter[0], car[head-1][1]+car[head+1][1])
car.remove(car[head+1])
car.remove(inter)
cal(car)
elif inter[1] =="-":
car[head-1] = (inter[0], car[head-1][1]-car[head+1][1])
car.remove(car[head+1])
car.remove(inter)
cal(car)
head += 1
return car[0][1]
print(cal(car))
OUT:
===
47

single line console output as a variable changes instead of one console.log per variable value?

Is there means in node.js to advance a counter within the console display to a single line, instead of a console.log output per line?
e.g.
let x = 1
while (x <= 10) {
console.log(`The value assigned to 'x' is now: ${x}`);
x++;
}
prints 10 lines for x = 1 through 10.
Is it possible instead to have a single line which remains static as the x value increments? As a use case, if the value of x incremented to one million, the console would display the one line until x was 1000000.
This does the trick for a single line:
const process = require('process');
let x = 1;
process.stdout.write(`The count is now at: ${x}`);
const counter = () => {
process.stdout.clearLine();
process.stdout.cursorTo(0);
x++;
process.stdout.write(`The count is now at: ${x}`);
if(x >= 10) {
clearInterval(cycle);
process.stdout.write('\n');
}
};
const cycle = setInterval(counter, 1000);
...and then there's this: https://github.com/sindresorhus/log-update

How to add an increasing integer ID to items in a Spark DStream

I am developing a Spark Streaming application where I want to have one global numeric ID per item in my data stream. Having an interval/RDD-local ID is trivial:
dstream.transform(_.zipWithIndex).map(_.swap)
This will result in a DStream like:
// key: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 || 0 | 1 | 2 | 3 | 4 || 0
// val: a | b | c | d | e | f | g | h | i || j | k | l | m | n || o
(where the double bar || indicates the beginning of a new RDD).
What I finally want to have is:
// key: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 || 9 | 10 | 11 | 12 | 13 || 14
// val: a | b | c | d | e | f | g | h | i || j | k | l | m | n || o
How can I do that in a safe and performant way?
This seems like a trivial task, but I feel it very hard to preserve state (state = "number of items seen so far") between RDDs. Here are two approaches I tried, updating the number of seen so far (plus the number in the current interval) using updateStateByKey with a bogus key:
val intervalItemCounts = inputStream.count().map((1, _))
// intervalItemCounts looks like:
// K: 1 || 1 || 1
// V: 9 || 5 || 1
val updateCountState: (Seq[Long], Option[ItemCount]) => Option[ItemCount] =
(itemCounts, maybePreviousState) => {
val previousState = maybePreviousState.getOrElse((0L, 0L))
val previousItemCount = previousState._2
Some((previousItemCount, previousItemCount + itemCounts.head))
}
val totalNumSeenItems: DStream[ItemCount] = intervalItemCounts.
updateStateByKey(updateCountState).map(_._2)
// totalNumSeenItems looks like:
// V: (0,9) || (9,14) || (14,15)
// The first approach uses a cartesian product with the
// 1-element state DStream. (Is this performant?)
val increaseRDDIndex1: (RDD[(Long, Char)], RDD[ItemCount]) =>
RDD[(Long, Char)] =
(streamData, totalCount) => {
val product = streamData.cartesian(totalCount)
product.map(dataAndOffset => {
val ((localIndex: Long, data: Char),
(offset: Long, _)) = dataAndOffset
(localIndex + offset, data)
})
}
val globallyIndexedItems1: DStream[(Long, Char)] = inputStream.
transformWith(totalNumSeenItems, increaseRDDIndex1)
// The second approach uses a take() output operation on the
// 1-element state DStream beforehand. (Is this valid?? Will
// the closure be serialized and shipped in every interval?)
val increaseRDDIndex2: (RDD[(Long, Char)], RDD[ItemCount]) =>
RDD[(Long, Char)] = (streamData, totalCount) => {
val offset = totalCount.take(1).head._1
streamData.map(keyValue => (keyValue._1 + offset, keyValue._2))
}
val globallyIndexedItems2: DStream[(Long, Char)] = inputStream.
transformWith(totalNumSeenItems, increaseRDDIndex2)
Both approaches give the correct result (with local[*] master), but I am wondering about performance (shuffle etc.), whether it works in a truly distributed environment and whether it shouldn't be a lot easier than that...

Access variable from outside of the function in jQuery

Please see my exaple:
var AbcVar = "abc";
function Abc(AbcVar){
console.log(AbcVar);
}
It this wrong way to allowing function to access external var?
Why is the output of console.log undefined?
It's time to meet Mr. Scoping.
Plainly speaking, scoping is an encapsulation of variables (note that in javascript, functions are also variables.) Now, in the imaginary language I just made up, the { character starts a scope and } ends it, variables are defined with simple equality (x = 42 for example):
{ |
x = 42; |
{ | |
y = "I'm in an inner scope!"; | |
x == 42; //true | |
{ | | |
x == 42; | | |
y == "I'm in an inner scope!"; | | |
| x, y, z are defined |
z = "pyramid time!"; | | |
y = y + "...not"; | | x, y are defined | x is defined
} | | |
y == "I'm in an inner scope!...not"; | |
//z is not defined | |
x = 4; | |
} | |
x == 4; |
//y is undefined |
//z is undefined |
} |
javascript has lexical scoping. Put simply, functions create a new scope:
var x = 42;
(funciton () {
x === 42;
var y = 5;
})();
//y is undefined
Now, there's an additional place where variables can be created, and that is in the function arguments. The two following functions behave the same (arguments is a pseudo-array containing the parameters passed into the function):
function parameterfull(a, b, c) {
//do stuff with a, b, c
}
function parameterless() {
var a = arguments[0], b = arguments[1], c = arguments[2];
//do stuff with a, b, c
}
If you happen to not pass an argument, its value will be undefined.
Now, using your function and the above translation:
var AbcVar = "abc";
function Abc() {
var AbcVar = arguments[0];
console.log(AbcVar);
}
So now you see why AbcVar is (sometimes) undefined inside the function.
tl;dr The function parameter AbcVar is overriding the global variable AbcVar, and since you didn't pass a value to the function, it's undefined (but only inside of the function, the global AbcVar remains the same.)
Inside the function, AbcVar will refer to the parameter AbcVar of the function. If you don't pass any parameter, the value will be undefined.
The parameter shadows the variable in higher scope with the same name. If you want to access it, you have to remove or rename the parameter. That said, you should always prefer passing arguments to functions (where possible).
hi you can change this to
var AbcVar = "abc";
function Abc(bbb){
console.log(AbcVar);
}
you can access external global var,if you write inside function,it assume that like;
var AbcVar = "abc";
function Abc(var AbcVar){
console.log(AbcVar);
}
so inside funciton AbcVar is new vaiable and null ,it shadow global AbcVar
if you run the function you've just created and pass it your AbcVar,
console.log(AbcVar);
it loggs "abc" as expected
Consider the following code
var AbcVar = "abc";
function logVariable(passedIn){
console.log(passedIn);
}
logVariable(AbcVar);
which creates a variable, a function to log the value of the variable, and then passes the variable to the logger which loggs it in the console
If you notice two lines on your interactive console after you run your logger function: abc followed by undefined
the first is the line printed when you call console.log() and the second is the value that logVariable returns after executing, which is undefined on success.

Resources