import { expect } from 'chai'; import { rm } from 'fs/promises'; import { readCsvFile, createCsvFile, Content, obj2csvRow, isCsvRow, } from '../../src/utils/csv'; import { getTestPath, randomString } from './utils'; describe('utils/csv', () => { let filePath: string; let title: string[]; let content: Content[]; beforeEach(async () => { filePath = getTestPath(`${randomString()}.csv`); title = ['name', 'sex', 'age']; content = [ { name: '张三', sex: '男', age: '12' }, { name: '李四', sex: '女', age: '15' }, { name: '王五', sex: '男', age: '23' }, { name: '王五', sex: '男', age: '23' }, { name: '凤吖头"^_^"', sex: '男', age: '["529449726414774272","529449734832742400","529449742395064321","529449746937495552"]' }, ]; await createCsvFile(filePath, title, content); }); afterEach(() => rm(filePath)); it('将csv文件内容以js对象的格式读取', async () => { const res = await readCsvFile(filePath); expect(res).to.deep.equals(content); }); it('将js对象转换为csv字符串', async () => { const str = await obj2csvRow( title, { name: '凤吖头"^_^"', sex: '男', age: '{"cids":["529449726414774272","529449734832742400","529449742395064321","529449746937495552"]}', }, ); expect(str).to.deep.equals('"凤吖头""^_^""","男","{""cids"":[""529449726414774272"",""529449734832742400"",""529449742395064321"",""529449746937495552""]}"\n'); }); /* eslint-disable @typescript-eslint/no-unused-expressions */ it('csv格式校验(不带引号)', async () => { expect(await isCsvRow('a,b,c,d', 4)).to.be.true; }); it('csv格式校验 (处理双引号)', async () => { expect(await isCsvRow('"a","b","c",d', 4)).to.be.true; }); it('csv格式校验(处理带换行符)', async () => { expect(await isCsvRow('"a","b","c",d\n', 4)).to.be.true; }); it('csv格式校验(处理空数据)', async () => { expect(await isCsvRow('"a","b","c",', 3)).to.be.false; }); it('csv格式校验(处理尾部逗号)', async () => { expect(await isCsvRow('"a","b","c""",', 3)).to.be.false; }); it('csv格式校验(处理头部逗号)', async () => { expect(await isCsvRow(',"a","b",c', 3)).to.be.false; }); it('csv格式校验(处理奇怪的引号)', async () => { expect(await isCsvRow('a,"b,c', 3)).to.be.false; }); it('csv格式校验(处理json)', async () => { expect(await isCsvRow('"a","b",c,"{""cids"":[""529449726414774272"",""529449734832742400""]"', 4)).to.be.true; }); });