gpt4 book ai didi

javascript - 节点环境的单元测试新 Blob enzyme

转载 作者:行者123 更新时间:2023-11-29 20:57:09 27 4
gpt4 key购买 nike

我正在尝试使用 Enzyme 测试一些下载功能,我的测试在节点环境中运行。但是我用的方法其实是dom api,如何在node env中测试。在我的代码中,我使用了 DOM API,例如 windows.URL.revokeObjectURLdocument.createElement('a') window.URL。 createObjectURL(new Blob([encodeWorkBook(wbout)], {type:'application/octet-stream'}))

   export const download = (url, name) => {
let a = document.createElement('a')
a.href = url
a.download = name
a.click()
window.URL.revokeObjectURL(url)
}

export const encodeWorkBook = string => {
const buf = new ArrayBuffer(string.length)
const unicodeArray = new Uint8Array(buf)

for (let i=0; i !== string.length; ++i)
unicodeArray[i] = string.charCodeAt(i) & 0xFF

return unicodeArray
}

export default (data, sheetName, bookType = OutPutFormats.xlsx) => {
import('xlsx').then(XLSX => {
const ws = XLSX.utils.json_to_sheet(data, {cellStyles: true})
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, ws, sheetName)

const wbout = XLSX.write(wb, {bookType, bookSST:true, type: 'binary'})

/* creates a DOMString containing a URL */

let url = window.URL.createObjectURL(new Blob([encodeWorkBook(wbout)], {type:'application/octet-stream'}))

download(url, `import.${bookType}`)
})
}

最佳答案

实际上,我们只需要在jsdom中添加global.Blob = function Blob(params) {return params},stub window.URL.createObjectURL = sinon.stub().returns (网址)

describe('encodeWorkBook', () => {
it('should encode work book to unicode array', () => {
encodeWorkBook(workBook).should.be.deep.equal(unicodeArray)
})
})

describe('exportToExcel', () => {
beforeEach(() => {
sinon.stub(XSLX.utils, 'json_to_sheet').withArgs(devices, {cellStyles: true}).returns({})
sinon.stub(XSLX.utils, 'book_new').returns({})
sinon.stub(XSLX.utils, 'book_append_sheet').withArgs({},{}, sheetName)
sinon.stub(XSLX, 'write').returns(workBook)
window.URL.createObjectURL = sinon.stub().returns(url)
file.download = sinon.spy()
})

afterEach(() => {
XSLX.utils.json_to_sheet.restore()
XSLX.utils.book_new.restore()
XSLX.utils.book_append_sheet.restore()
XSLX.write.restore()
})

it('should call download with correct url and output extension', async () => {
Object.values(OutputFormats).forEach(async format => {
await exportToExcel(devices, sheetName, format)

file.download.args[0][0].should.equal(url)
file.download.args[0][1].should.equal(`import.${format}`)
file.download.calledOnce.should.be.true
})
})

it('should call download with default output extension', async () => {
await exportToExcel(devices, sheetName)

file.download.args[0][1].should.equal(`import.${OutputFormats.xlsx}`)
})
})

关于javascript - 节点环境的单元测试新 Blob enzyme ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48706338/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com