0

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');
});
2
  • 1
    Did you mean to reference calculation.sayOperation? In the scope of the Jest test, sayOperation has not been declared which is why you are getting that error. Commented Feb 27, 2021 at 22:23
  • I did change it to calculation.sayOperation and there is an error said undefined Commented Feb 27, 2021 at 22:45

1 Answer 1

1

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')

Sign up to request clarification or add additional context in comments.

2 Comments

I did change it but there is an error said undefined
see edit - you need to return the results of addOperationToName and of sayOperation, previously it was just console.log-ing it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.