mardi 2 mars 2021

Strategy Pattern implementation in JavaScript code error

I have the Calculation.js file, CalculationStrategy.js, and CalculationStrategyB.js.

I want to implement the Strategy Pattern to these files. However, when I used Jest to test the files. I have an error that this.stragtegy.doOperation is not a function.

I did follow the tutorial to implement the Strategy Pattern by using the Calculation file as a base but I don't know why this happens.

Calculation.js

class Calculation {
constructor(a, b, op) {
    this.a = a;
    this.b = b;
    this.op = op;
    this.stragtegy = null;
}

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 an operation';
        return fn(operation);
    }
}

sayOperation(name){
    return name;
}

obtainStructor(){
    return this.a +' '+ this.b;
}

set strategy(stragtegy){
    this.stragtegy = stragtegy;
}

doOperation(){
    return this.stragtegy.doOperation();
}
}
module.exports = Calculation;

CalculationStrategy.js

class CalculationStrategy{
doAction(){
    return 'This is Calculation Strategy 1';
}
}
module.exports = CalculationStrategy;

CalculationStrategyB.js

class CalculationStrategyB{
doAction(){
    return 'This is Calculation Strategy 2';
}
}
module.exports = CalculationStrategyB;

CalculationStrategy.test.js

const calculation = require('../src/models/Calculation');
const calculationStrategy = require('../src/CalculationStrategy');
const calculationStrategyB = require('../src/CalculationStrategyB');
const Product = require('../src/Operations/Product');

test('Test Strategy of Calculation', () => {
//I need to test the get results function
let op = Product;
let customCalculation = new calculation(1,2, op);
const strategy = new calculationStrategy();
const strategyB = new calculationStrategyB();
customCalculation.stragtegy = strategy;
expect(customCalculation.doOperation()).toBe('This is Calculation Strategy 1');
customCalculation.stragtegy = strategyB;
expect(customCalculation.doOperation()).toBe('This is Calculation Strategy 2');
});

Aucun commentaire:

Enregistrer un commentaire