我制作了非常简单的画布并用摩卡咖啡测试它们。我的做法与 Juho Vepsäläinen 类似,但我的看起来更简单一些。我在ec2015上写的。
CanvasMock 类:
import ContextMock from './ContextMock.js'
export default class {
constructor (width, height)
{
this.mock = [];
this.width = width;
this.height = height;
this.context = new ContextMock(this.mock);
}
getContext (string)
{
this.mock.push('[getContext ' + string + ']')
return this.context
}
}
ContextMock 类:
export default class {
constructor(mock)
{
this.mock = mock
}
beginPath()
{
this.mock.push('[beginPath]')
}
moveTo(x, y)
{
this.mock.push('[moveTo ' + x + ', ' + y + ']')
}
lineTo(x, y)
{
this.mock.push('[lineTo ' + x + ', ' + y + ']')
}
stroke()
{
this.mock.push('[stroke]')
}
}
一些评估 mock 本身功能的 mocha 测试:
describe('CanvasMock and ContextMock', ()=> {
it('should be able to return width and height', ()=> {
let canvas = new CanvasMock(500,600)
assert.equal(canvas.width, 500)
assert.equal(canvas.height, 600)
})
it('should be able to update mock for getContext', ()=> {
let canvas = new CanvasMock(500,600)
let ctx = canvas.getContext('2d')
assert.equal(canvas.mock, '[getContext 2d]')
})
})
评估返回画布的函数的功能的 mocha 测试:
import Myfunction from 'MyFunction.js'
describe('MyFuntion', ()=> {
it('should be able to return correct canvas', ()=> {
let testCanvas = new CanvasMock(500,600)
let ctx = testCanvas.getContext('2d')
ctx.beginPath()
ctx.moveTo(0,0)
ctx.lineTo(8,8)
ctx.stroke()
assert.deepEqual(MyFunction(new CanvasMock(500,600), 8, 8), canvas.mock, [ '[getContext 2d]', '[beginPath]', '[moveTo 0, 0]', [lineTo 8, 8]', '[stroke]' ])
})
所以在本例中,myfunction 将您传入的画布作为参数 ( Myfunction(new CanvasMock(500,600), 8, 8) ) 并在其上写入从 0,0 到任何值的行您作为参数( Myfunction(new CanvasMock(500,600),** 8, 8**) )传入,然后返回编辑后的画布。
因此,当您在现实生活中使用该函数时,您可以传入一个实际的画布,而不是一个画布模拟,然后它会运行相同的方法,但会执行实际的画布操作。
了解模拟 here