const fs = require('fs-extra'); const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); const nameItem = 'Pallet'; const collectionName = 'user'; let obj = {}; const STORAGE_IMAGE_USER = 'storage/image/user'; const _23_F2 = '23/f2'; const FULL_23_F2 = `full/${_23_F2}`; describe('loopback model Image', () => { const userId = 1107; const activeCtx = { accessToken: {userId: userId}, http: { req: { headers: {origin: 'http://localhost'}, }, }, }; beforeAll(async() => { const {name: fileName, id: entityId} = await models.Item.findOne({where: {name: nameItem}}); obj = { collectionName, srcFile: 'front/core/directives/no-image.png', fileName, entityId, }; }); beforeEach(() => { spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ active: activeCtx, }); }); it('should handle folder destination', async() => { try { const {name, dstDir} = await models.Image.handleFolderDestination(obj.fileName); expect(name).toEqual(nameItem); expect(dstDir).toEqual(`${_23_F2}`); const collectionDir = await models.Image.getCollectionDir(collectionName); expect(collectionDir).toEqual(`${STORAGE_IMAGE_USER}`); } catch (e) { throw new Error(e); } }); it('should handle full size path', async() => { try { const {dstDir} = await models.Image.handleFolderDestination(obj.fileName); const collectionDir = await models.Image.getCollectionDir(collectionName); const _fullSizePath = models.Image.getFullSizePath(obj.fileName, collectionDir, dstDir); const {fullSizePath, toFullSizePath, toFullSizeOriginalPath} = _fullSizePath; expect(fullSizePath).toEqual(`${STORAGE_IMAGE_USER}/${FULL_23_F2}`); expect(toFullSizePath).toEqual(`${STORAGE_IMAGE_USER}/${FULL_23_F2}/${nameItem}`); expect(toFullSizeOriginalPath).toEqual(`${STORAGE_IMAGE_USER}/full/${nameItem}`); } catch (e) { throw new Error(e); } }); it('should resize', async() => { try { await models.Image.resize(obj); const fileExists = await fs.exists(`${STORAGE_IMAGE_USER}/${FULL_23_F2}/${nameItem}.png`); expect(fileExists).toBeTrue(); const linkExists = await fs.readlink(`${STORAGE_IMAGE_USER}/full/${nameItem}`); expect(linkExists).toEqual(`${STORAGE_IMAGE_USER}/${FULL_23_F2}/${nameItem}`); } catch (e) { throw new Error(e); } }); afterAll(async() => { try { await fs.unlink(`${STORAGE_IMAGE_USER}/full/${nameItem}`); await fs.unlink(`${STORAGE_IMAGE_USER}/520x520/${nameItem}`); await fs.unlink(`${STORAGE_IMAGE_USER}/1600x1600/${nameItem}`); } catch (e) { throw new Error(e); } }); });