From f99b2fbfb2711f71c507f917bad983d51f64c75a Mon Sep 17 00:00:00 2001 From: David Katz <15Dkatz@shcp.edu> Date: Tue, 27 Sep 2022 14:36:21 -0700 Subject: [PATCH] Chain Validation | Tests --- blockchain.test.js | 46 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/blockchain.test.js b/blockchain.test.js index 7422d32..1bd3f01 100644 --- a/blockchain.test.js +++ b/blockchain.test.js @@ -2,7 +2,11 @@ const Blockchain = require('./blockchain'); const Block = require('./block'); describe('Blockchain', () => { - const blockchain = new Blockchain(); + let blockchain; + + beforeEach(() => { + blockchain = new Blockchain(); + }); it('contains a `chain` Array instance', () => { expect(blockchain.chain instanceof Array).toBe(true); @@ -18,4 +22,44 @@ describe('Blockchain', () => { expect(blockchain.chain[blockchain.chain.length-1].data).toEqual(newData); }); + + describe('isValidChain()', () => { + describe('when the chain does not start with the genesis block', () => { + it('returns false', () => { + blockchain.chain[0] = { data: 'fake-genesis' }; + + expect(Blockchain.isValidChain(blockchain.chain)).toBe(false); + }); + }); + + describe('when the chain starts with the genesis block and has multiple blocks', () => { + beforeEach(() => { + blockchain.addBlock({ data: 'Bears' }); + blockchain.addBlock({ data: 'Beets' }); + blockchain.addBlock({ data: 'Battlestar Galactica' }); + }); + + describe('and a lastHash reference has changed', () => { + it('returns false', () => { + blockchain.chain[2].lastHash = 'broken-lastHash'; + + expect(Blockchain.isValidChain(blockchain.chain)).toBe(false); + }); + }); + + describe('and the chain contains a block with an invalid field', () => { + it('returns false', () => { + blockchain.chain[2].data = 'some-bad-and-evil-data'; + + expect(Blockchain.isValidChain(blockchain.chain)).toBe(false); + }); + }); + + describe('and the chain does not contain any invalid blocks', () => { + it('returns true', () => { + expect(Blockchain.isValidChain(blockchain.chain)).toBe(true); + }); + }); + }); + }); });