|
| 1 | +import { isAbsolute, resolve } from 'node:path' |
| 2 | +import { runInNewContext } from 'node:vm' |
| 3 | + |
| 4 | +import Taro from '@tarojs/api' |
| 5 | +import { rollup } from 'rollup' |
| 6 | + |
| 7 | +const publicApi = resolve(__dirname, '../../../taro-platform-harmony-hybrid/dist/api/index.js') |
| 8 | +const consumer = '\0save-file-to-disk-consumer' |
| 9 | + |
| 10 | +afterEach(() => jest.restoreAllMocks()) |
| 11 | + |
| 12 | +it('reports saveFileToDisk as unsupported in Harmony Hybrid without requesting a download', async () => { |
| 13 | + jest.replaceProperty(process.env, 'NODE_ENV', 'production') |
| 14 | + jest.spyOn(console, 'warn').mockImplementation(() => {}) |
| 15 | + const click = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) |
| 16 | + const unsupported = jest.fn() |
| 17 | + const options = { filePath: '/reports/monthly.csv' } |
| 18 | + |
| 19 | + // Bundle a named import from the same generated entry that apps consume. |
| 20 | + const bundle = await rollup({ |
| 21 | + input: consumer, |
| 22 | + external: (id, importer) => !!importer && !id.startsWith('.') && !isAbsolute(id), |
| 23 | + treeshake: { moduleSideEffects: false }, |
| 24 | + plugins: [{ |
| 25 | + name: 'save-file-to-disk-consumer', |
| 26 | + resolveId: id => id === consumer ? id : null, |
| 27 | + load: id => id === consumer ? `export { saveFileToDisk } from ${JSON.stringify(publicApi)}` : null, |
| 28 | + }], |
| 29 | + }) |
| 30 | + const exports: Pick<typeof Taro, 'saveFileToDisk'> = Object.create(null) |
| 31 | + try { |
| 32 | + const { output } = await bundle.generate({ format: 'cjs', exports: 'named', interop: 'auto' }) |
| 33 | + runInNewContext(output[0].code, { exports, require, process, console, document, window }) |
| 34 | + } finally { |
| 35 | + await bundle.close() |
| 36 | + } |
| 37 | + |
| 38 | + Taro.eventCenter.on('__taroNotSupport', unsupported) |
| 39 | + try { |
| 40 | + await expect(exports.saveFileToDisk(options)).resolves.toEqual({ errMsg: '暂时不支持 API' }) |
| 41 | + expect(unsupported).toHaveBeenCalledWith({ |
| 42 | + name: 'saveFileToDisk', |
| 43 | + args: [options], |
| 44 | + type: 'method', |
| 45 | + category: 'temporarily', |
| 46 | + }) |
| 47 | + expect(click).not.toHaveBeenCalled() |
| 48 | + } finally { |
| 49 | + Taro.eventCenter.off('__taroNotSupport', unsupported) |
| 50 | + } |
| 51 | +}) |
0 commit comments