如何使用Sinon JS进行动态导入

时间:2018-02-13 11:05:42

标签: javascript sinon enzyme sinon-chai chai-enzyme

我尝试用sinon js导入,如何做到这一点, import XLSX from 'xlsx' beforeEach(() => sinon.stub(sheetJS).resolve({})) - 对我不起作用,并且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}`)
})

1 个答案:

答案 0 :(得分:0)

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