Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions packages/taro-h5/__tests__/canvas/export.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { canvasToTempFilePath } from '../../src/api/canvas/canvasToTempFilePath'
import * as utils from '../../src/utils'

describe('canvas export', () => {
let container: HTMLDivElement
let canvas: HTMLCanvasElement
let otherCanvas: HTMLCanvasElement

beforeEach(() => {
container = document.createElement('div')
otherCanvas = document.createElement('canvas')
otherCanvas.setAttribute('canvas-id', 'other')
container.appendChild(otherCanvas)
canvas = document.createElement('canvas')
canvas.setAttribute('canvas-id', 'test')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

建议在这里再添加一个不同 canvas-id 的 canvas,并分别 spy 两个 canvas 的 toDataURL。当前测试容器里只有一个 canvas,即使实现错误地始终选择第一个 canvas,测试也会通过,无法验证 canvasId 是否真正生效。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

感谢建议,已在 790b975 中添加另一个 canvas-id="other" 的画布,并将其放在目标画布之前。成功导出测试分别 spy 两个画布的 toDataURL,断言目标画布调用一次、非目标画布不调用,且返回目标画布的数据,覆盖误选第一个画布的情况。

Canvas 相关 2 个测试套件、15 个用例全部通过,修改文件 ESLint 和差异检查通过,烦请复查。

container.appendChild(canvas)
jest.spyOn(utils, 'findDOM').mockReturnValue(container)
})

afterEach(() => jest.restoreAllMocks())

test.each(['missing canvas', 'missing container'])('rejects a %s', async scenario => {
if (scenario === 'missing container') jest.mocked(utils.findDOM).mockReturnValue(undefined)
await expect(canvasToTempFilePath({ canvasId: 'missing' })).rejects.toEqual({
errMsg: 'canvasToTempFilePath:fail canvas missing is not available'
})
})

test('calls fail and complete once without reporting success for a missing canvas', async () => {
const success = jest.fn()
const fail = jest.fn()
const complete = jest.fn()
const expected = { errMsg: 'canvasToTempFilePath:fail canvas missing is not available' }
await expect(canvasToTempFilePath({ canvasId: 'missing', success, fail, complete })).resolves.toEqual(expected)
expect(success).not.toHaveBeenCalled()
expect(fail).toHaveBeenCalledTimes(1)
expect(fail).toHaveBeenCalledWith(expected)
expect(complete).toHaveBeenCalledTimes(1)
expect(complete).toHaveBeenCalledWith(expected)
})

test('routes DOM lookup failures through the failure handler', async () => {
jest.mocked(utils.findDOM).mockImplementation(() => { throw new Error('Canvas lookup failed') })

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里目前只验证了 Promise reject,没有覆盖 callback 模式。建议传入 fail、complete 和 success,断言 fail/complete 各调用一次且 success 不调用,以防止后续把 DOM 查找移出 try/catch 后破坏 callback 调用方。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已在 790b975 中保留原有 Promise reject 测试,并补充 DOM 查找抛错时的回调用例:同时传入 success、fail、complete,断言 fail 和 complete 各调用一次、错误参数正确,success 不调用;同时验证按现有 MethodHandler 约定,提供回调后 Promise resolve 为失败结果。Canvas 相关 15 个用例全部通过,感谢 review。

await expect(canvasToTempFilePath({ canvasId: 'test' })).rejects.toEqual({
errMsg: 'canvasToTempFilePath:fail Canvas lookup failed'
})
})

test('routes invalid selector errors through the failure handler', async () => {
await expect(canvasToTempFilePath({ canvasId: '"]' })).rejects.toEqual({

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

建议补充 callback 断言:fail 和 complete 应各调用一次,success 不应调用。当前测试只覆盖了无 callback 时的 Promise reject,无法验证异常路径的完整回调语义。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已在 790b975 中保留非法选择器的 Promise reject 测试,并新增回调模式覆盖:断言 fail 和 complete 各调用一次且收到失败结果,success 不调用,同时确认 Promise resolve 为同一失败结果。Canvas 相关 15 个用例全部通过,烦请复查。

errMsg: expect.stringMatching(/^canvasToTempFilePath:fail /)
})
})

test.each(['DOM lookup failure', 'invalid selector'])('calls failure callbacks once for a %s', async scenario => {
const success = jest.fn()
const fail = jest.fn()
const complete = jest.fn()
const canvasId = scenario === 'invalid selector' ? '"]' : 'test'
if (scenario === 'DOM lookup failure') {
jest.mocked(utils.findDOM).mockImplementation(() => { throw new Error('Canvas lookup failed') })
}
const expected = {
errMsg: scenario === 'DOM lookup failure'
? 'canvasToTempFilePath:fail Canvas lookup failed'
: expect.stringMatching(/^canvasToTempFilePath:fail /)
}

await expect(canvasToTempFilePath({ canvasId, success, fail, complete })).resolves.toEqual(expected)
expect(success).not.toHaveBeenCalled()
expect(fail).toHaveBeenCalledTimes(1)
expect(fail).toHaveBeenCalledWith(expected)
expect(complete).toHaveBeenCalledTimes(1)
expect(complete).toHaveBeenCalledWith(expected)
})

test('reports security errors from exporting a tainted canvas', async () => {
jest.spyOn(canvas, 'toDataURL').mockImplementation(() => {
throw new DOMException('Canvas is tainted', 'SecurityError')
})
const fail = jest.fn()
const complete = jest.fn()
const expected = { errMsg: 'canvasToTempFilePath:fail Canvas is tainted' }
await expect(canvasToTempFilePath({ canvasId: 'test', fail, complete })).resolves.toEqual(expected)
expect(fail).toHaveBeenCalledTimes(1)
expect(fail).toHaveBeenCalledWith(expected)
expect(complete).toHaveBeenCalledTimes(1)
expect(complete).toHaveBeenCalledWith(expected)
})

test.each([
[undefined, 'image/png'],
['png', 'image/png'],
['jpg', 'image/jpeg']
] as const)('exports %s with the requested quality', async (fileType, mimeType) => {
const tempFilePath = `data:${mimeType};base64,test`
const toDataURL = jest.spyOn(canvas, 'toDataURL').mockReturnValue(tempFilePath)
const otherToDataURL = jest.spyOn(otherCanvas, 'toDataURL').mockReturnValue(`data:${mimeType};base64,other`)
const success = jest.fn()
const fail = jest.fn()
const complete = jest.fn()
const expected = { errMsg: 'canvasToTempFilePath:ok', tempFilePath }
await expect(canvasToTempFilePath({ canvasId: 'test', fileType, quality: 0.8, success, fail, complete })).resolves.toEqual(expected)
expect(toDataURL).toHaveBeenCalledTimes(1)
expect(toDataURL).toHaveBeenCalledWith(mimeType, 0.8)
expect(otherToDataURL).not.toHaveBeenCalled()
expect(success).toHaveBeenCalledTimes(1)
expect(success).toHaveBeenCalledWith(expected)
expect(fail).not.toHaveBeenCalled()
expect(complete).toHaveBeenCalledTimes(1)
expect(complete).toHaveBeenCalledWith(expected)
})
})
9 changes: 5 additions & 4 deletions packages/taro-h5/src/api/canvas/canvasToTempFilePath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ import { MethodHandler } from '../../utils/handler'
*/
export const canvasToTempFilePath: typeof Taro.canvasToTempFilePath = ({ canvasId, fileType, quality, success, fail, complete }, inst) => {
const handle = new MethodHandler({ name: 'canvasToTempFilePath', success, fail, complete })
const el = findDOM(inst) as HTMLElement
const canvas = el?.querySelector(`canvas[canvas-id="${canvasId}"]`) as HTMLCanvasElement

try {
const dataURL = canvas?.toDataURL(`image/${(fileType === 'jpg' ? 'jpeg' : fileType) || 'png'}`, quality)
const el = findDOM(inst) as HTMLElement
const canvas = el?.querySelector(`canvas[canvas-id="${canvasId}"]`) as HTMLCanvasElement
if (!canvas) throw new Error(`canvas ${canvasId} is not available`)

const dataURL = canvas.toDataURL(`image/${(fileType === 'jpg' ? 'jpeg' : fileType) || 'png'}`, quality)
return handle.success({
tempFilePath: dataURL
})
Expand Down
Loading