I have a class named Calculation which I added two functions are addOperationToName() and sayOperation() as examples of the Decorator design pattern. However, when I test it using Jest, I got an error that 'fn is not a function'. Can someone help me?
Calculation.js
class Calculation {
constructor(a, b, op) {
this.a = a;
this.b = b;
this.op = op;
}
static Create(a, b, op){
return new Calculation(a, b, op);
}
GetResults() {
return this.op(this.a,this.b)
}
addOperationToName(fn){
return function(name){
const operation = name + ' is a operation';
fn(operation);
}
}
sayOperation(name){
console.log(name);
}
}
module.exports = Calculation;
Calculation.test.js
const Calculation = require('../src/models/Calculation');
test('Test say name for Product operation', () => {
let op = Product;
let calculation = new Calculation(1,2,op);
let sayTest = calculation.addOperationToName(calculation.sayOperation());
expect(sayTest('Multiply')).toBe('Multiply is an operation');
});
You are supposed to pass a function to addOperationToName
, right now you are returning the result of a function - just change calculation.addOperationToName(calculation.sayOperation());
to calculation.addOperationToName(calculation.sayOperation);
class Calculation { constructor(a, b, op) { this.a = a; this.b = b; this.op = op; } static Create(a, b, op){ return new Calculation(a, b, op); } GetResults() { return this.op(this.a,this.b) } addOperationToName(fn){ return function(name){ const operation = name + ' is a operation'; return fn(operation); } } sayOperation(name){ console.log(name); return name; } } let calculation = new Calculation(1,2,null); let sayTest = calculation.addOperationToName(calculation.sayOperation); console.log(sayTest('Multiply') === 'Multiply is a operation')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.