我很难使用 jest 对 while 循环进行一些测试。这是我想测试但不知道该怎么做的代码。
const SHA256 = require('crypto-js/sha256')
class Block {
constructor(index, timestamp, data, prevHash = "") {
this.index = index
this.timestamp = timestamp
this.data = data
this.prevHash = prevHash
this.hash = this.calculateHash()
this.nonce = 0
}
calculateHash() {
return SHA256(this.index + this.prevHash + this.timestamp + JSON.stringify(this.data) + this.nonce).toString()
}
mineBlock(difficulty) {
while(this.hash.substring(0, difficulty) !== Array(difficulty + 1).join('0')) {
this.nonce++
this.hash = this.calculateHash()
}
}
}
module.exports = Block
这是我到目前为止所做的
const Block = require('../block')
const BlockClass = new Block()
describe('Block Class', () => {
it('constructor', () => {
const obj = new Block(1, 2, 3, 4, 0)
expect(obj.index).toBe(1)
expect(obj.timestamp).toBe(2)
expect(obj.data).toBe(3)
expect(obj.prevHash).toBe(4)
expect(obj.nonce).toBe(0)
})
})
describe('hash', () => {
it('should be string', () => {
expect(typeof BlockClass.calculateHash()).toBe('string')
})
})
我对玩笑和单元测试还很陌生,我发现拥有它非常好的技能。