簡體   English   中英

如何使用Sinon JS存根動態導入

[英]How to stub dynamical import with Sinon JS

我嘗試使用sinon js存根導入,如何實際地做到這一點, import XLSX from 'xlsx' beforeEach(() => sinon.stub(sheetJS).resolve({})) -對我不起作用,我resolve is not a function cath錯誤resolve is not a function

 export default (data, sheetName, bookType = OutputFormats.xlsx) =>
import('xlsx').then(XLSX => {
    /* create worksheet from data */
    const ws = XLSX.utils.json_to_sheet(data, {cellStyles: true})

    /* create new workbook and add worksheet */
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, sheetName)

    /* generate with and height of cells in .xlsx file */
    const wscols = Object.keys(data[0]).map(key => key = {wch: key.length + 2})

    const wsrows = new Array(data.length).fill({hpt: 24})
    ws['!cols'] = wscols
    ws['!rows'] = wsrows

    /* write a workbook */
    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'}))

    file.download(url, `import.${bookType}`)
})
import XSLX from 'xlsx'

import exportToExcel, {encodeWorkBook} from '../../src/utils/exportToExcel'
import file from '../../src/utils/file'
import OutputFormats from '../../src/constants/outputFormats'




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}`)
        })
    })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM