I defined Blockchain class:
class Blockchain {
constructor() {
// chain has to be validated all the time. new block should be legit
this.chain = [Block.getGenesisBlock()];
}
addBlock({ data }) {
const newBlock = Block.mineBlock({ // this function is working properly
lastBlock: this.chain[this.chain.length - 1],
data,
});
this.chain.push(newBlock);
}
// ************ STATIC METHOD IS FAILING TEST *******************
getLastBlock() {
return this.chain[this.chain.length - 1];
}
}
Test case is passing with non-static getLastBlock
it("adds a new block to chain", () => {
const newBlockData = "datala";
blockchain.addBlock({ data: newBlockData });
expect(blockchain.getLastBlock().data).toEqual(newBlockData);
});
However if I define static method:
static getLastBlock() {
return this.chain[this.chain.length - 1];
}
And calling this method with Blockchain class in test file:
it("adds a new block to chain", () => {
const newBlockData = "datala";
blockchain.addBlock({ data: newBlockData });
expect(Blockchain.getLastBlock().data).toEqual(newBlockData);
});
I could not figure out why. I thought I understood everything about this and class in JavaScript.

Aucun commentaire:
Enregistrer un commentaire