How to use fs.statAsync method in Cypress

Best JavaScript code snippet using cypress

fileIO.test.js

Source:fileIO.test.js Github

copy

Full Screen

1//Reset the mock functions and the cached modules before each test2beforeEach(() => {3 jest.clearAllMocks();4});5//Test creating a writeable file stream6describe('testing creating a writeable file stream', () => {7 jest.resetModules();8 9 //Mock the fs module10 jest.doMock('fs', () => ({ createWriteStream: jest.fn(), bob: 2 }));11 12 const fs = require('fs');13 const fileIO = require('../../common/fileIO');14 15 //Create mock file stream16 const mockFileStream = { id: 'Mock file stream' };17 18 //Mock fs.createWriteStream() to return the mock file stream19 fs.createWriteStream.mockReturnValueOnce(mockFileStream);20 21 //Test that the writeable file stream is created succesfully22 test('the writeable file stream can be created', () => {23 const fileName = './data/dataFile.dat';24 25 //Call the function to create a writeable file stream26 const fileStream = fileIO.createWriteableFileStream(fileName);27 28 //Verify that the file stream object is correct29 expect(fileStream).toBe(mockFileStream);30 31 //Verify that fs.createWriteStream() was called once with the32 //correct arguments33 expect(fs.createWriteStream).toHaveBeenCalledTimes(1);34 expect(fs.createWriteStream).toHaveBeenCalledWith(fileName);35 });36});37//Test ensuring that a directory exists38describe('testing ensuring that a directory exists', () => {39 jest.resetModules();40 41 //Mock the fs module42 jest.doMock('fs', () => ({ statAsync: jest.fn() }));43 44 //Mock the mkdirp function45 jest.doMock('mkdirp', () => jest.fn()); 46 47 const fs = require('fs');48 const fileIO = require('../../common/fileIO');49 const mkdirp = require('mkdirp');50 51 const testDirectory = "data/output";52 53 //Test that a non-existent directory is automatically created54 test('an non-existent directory is created', () => {55 //Mock the stat function so that it indicates that the directory56 //doesn't exist57 fs.statAsync.mockReturnValueOnce(Promise.reject(new Error('does not exist')));58 59 //Mock the mkdirp function to return a successful promise60 mkdirp.mockReturnValueOnce(Promise.resolve());61 62 expect.hasAssertions();63 64 //Call the function to ensure that the file directory exists65 return expect(fileIO.ensureDirectoryExists(testDirectory)).resolves.not.toBeDefined()66 .then(() => {67 //Verify that fs.statAsync was only called once68 expect(fs.statAsync).toHaveBeenCalledTimes(1);69 70 //Verify that fs.statAsync was called with the correct arguments71 expect(fs.statAsync).toHaveBeenCalledWith(testDirectory);72 73 //Verify that mkdirp was called once74 expect(mkdirp).toHaveBeenCalledTimes(1);75 76 //Verify that mkdirp was called with the correct arguments77 expect(mkdirp).toHaveBeenCalledWith(testDirectory);78 });79 });80 //Test that no directory is created when it already exists81 test('no directories are created when the directory already exists', () => {82 //Mock the stat function so that it indicates that the directory83 //does exist84 fs.statAsync.mockReturnValueOnce(Promise.resolve({85 isDirectory: () => true86 }));87 88 expect.hasAssertions();89 90 //Call the function to ensure that the file directory exists91 return expect(fileIO.ensureDirectoryExists(testDirectory)).resolves.not92 .toBeDefined().then(() => {93 //Verify that fs.statAsync was only called once94 expect(fs.statAsync).toHaveBeenCalledTimes(1);95 96 //Verify that fs.statAsync was called with the correct arguments97 expect(fs.statAsync).toHaveBeenCalledWith(testDirectory);98 99 //Verify that mkdirp was never called100 expect(mkdirp).not.toHaveBeenCalled();101 });102 });103 104 //Test what happens when there's a file with the same name as the directory105 test('no directories are created when a file with the same name as the ' + 106 'directory already exists', () => {107 //Mock the stat function so that it indicates that the directory108 //does exist109 fs.statAsync.mockReturnValueOnce(Promise.resolve({110 isDirectory: () => false111 }));112 113 expect.hasAssertions();114 115 //Call the function to ensure that the file directory exists116 return expect(fileIO.ensureDirectoryExists(testDirectory)).rejects117 .toBeDefined().catch((error) => {118 expect(error.message).toMatch('already exists');119 });120 });121 122 //Test what happens when there's an error when creating a non-existent123 //directory124 test('promise rejects when there\'s an error when creating the directory', () => {125 const errorMessage = 'Could not create directory';126 127 //Mock the stat function so that it indicates that the directory128 //doesn't exist129 fs.statAsync.mockReturnValueOnce(Promise.reject(new Error('does not exist')));130 131 //Mock the mkdirp function to return a rejected promise132 mkdirp.mockReturnValueOnce(Promise.reject(new Error(errorMessage)));133 134 expect.hasAssertions();135 136 //Call the function to ensure that the file directory exists137 return expect(fileIO.ensureDirectoryExists(testDirectory)).rejects138 .toHaveProperty('message', errorMessage).then((error) => {139 //Verify that fs.statAsync was only called once140 expect(fs.statAsync).toHaveBeenCalledTimes(1);141 142 //Verify that fs.statAsync was called with the correct arguments143 expect(fs.statAsync).toHaveBeenCalledWith(testDirectory);144 145 //Verify that mkdirp was called once146 expect(mkdirp).toHaveBeenCalledTimes(1);147 148 //Verify that mkdirp was called with the correct arguments149 expect(mkdirp).toHaveBeenCalledWith(testDirectory);150 });151 }); 152});153//Test ensuring that a directory for a file exists154describe('testing ensuring that a directory for a file exists', () => {155 jest.resetModules();156 //Mock the fs module157 jest.doMock('fs', () => ({ statAsync: jest.fn() })); 158 159 //Mock the path module160 jest.doMock('path', () => ({ dirname: jest.fn() }));161 162 //Mock the mkdirp function163 jest.doMock('mkdirp', () => jest.fn()); 164 165 const fs = require('fs');166 const fileIO = require('../../common/fileIO');167 const path = require('path');168 const mkdirp = require('mkdirp');169 170 const fileName = "data/output/dataFile.txt";171 const fileDirectory = "data/output";172 const errorMessage = "test error message";173 174 //Tests what happens when a file's directory is created succesfully175 test('the file\'s directory is created successfully', () => {176 //Mock the stat function so that it indicates that the directory177 //doesn't exist178 fs.statAsync.mockReturnValueOnce(Promise.reject(new Error('does not exist')));179 180 //Mock the mkdirp function to return a successful promise181 mkdirp.mockReturnValueOnce(Promise.resolve());182 183 //Mock path.dirname to return the correct directory184 path.dirname.mockReturnValueOnce(fileDirectory);185 186 expect.hasAssertions();187 188 //Call the function to ensure that the file directory exists189 return expect(fileIO.ensureFilePathExists(fileName)).resolves.not.toBeDefined()190 .then(() => {191 //Verify that path.dirname was called with the192 //correct arguments193 expect(path.dirname).toHaveBeenCalledTimes(1);194 expect(path.dirname).toHaveBeenCalledWith(fileName);195 196 //Verify that fs.statAsync was called with the correct arguments197 expect(fs.statAsync).toHaveBeenCalledTimes(1);198 expect(fs.statAsync).toHaveBeenCalledWith(fileDirectory);199 200 //Verify that mkdirp was called with the correct arguments201 expect(mkdirp).toHaveBeenCalledTimes(1);202 expect(mkdirp).toHaveBeenCalledWith(fileDirectory);203 });204 });205 //Test what happens when a file's directory was unable to be created206 test('the file\'s directory could not be created', () => {207 //Mock the stat function so that it indicates that the directory208 //doesn't exist209 fs.statAsync.mockReturnValueOnce(Promise.reject(new Error('does not exist')));210 211 //Mock the mkdirp function to return a rejected promise212 mkdirp.mockReturnValueOnce(Promise.reject(new Error(errorMessage)));213 214 //Mock path.dirname to return the correct directory215 path.dirname.mockReturnValueOnce(fileDirectory);216 217 expect.hasAssertions();218 219 //Call the function to ensure that the file directory exists220 return expect(fileIO.ensureFilePathExists(fileName)).rejects221 .toHaveProperty('message', errorMessage).then((error) => {222 //Verify that path.dirname was called with the223 //correct arguments224 expect(path.dirname).toHaveBeenCalledTimes(1);225 expect(path.dirname).toHaveBeenCalledWith(fileName);226 227 //Verify that fs.statAsync was called with the correct arguments228 expect(fs.statAsync).toHaveBeenCalledTimes(1);229 expect(fs.statAsync).toHaveBeenCalledWith(fileDirectory);230 231 //Verify that mkdirp was called with the correct arguments232 expect(mkdirp).toHaveBeenCalledTimes(1);233 expect(mkdirp).toHaveBeenCalledWith(fileDirectory);234 }); 235 });236 ...

Full Screen

Full Screen

props.spec.js

Source:props.spec.js Github

copy

Full Screen

1/* eslint-env jest */2jest.mock('fs', () => ({3 readFileAsync: jest.fn(async () => undefined),4 statAsync: jest.fn(async () => ({ isDirectory: () => false })),5}))6jest.mock('react-docgen', () => ({ parse: jest.fn() }))7jest.mock('./resolvers', () => ({ indexResolver: 'indexResolver', componentResolver: 'componentResolver' }))8const fs = require('fs')9const docgen = require('react-docgen')10const service = require('./props')11const toRedux = path => [12 // dispatch13 undefined,14 // getState15 () => ({16 component: {17 path: {18 absolute: {19 full: path,20 },21 },22 },23 }),24]25describe('server/api/models/docgen', () => {26 beforeEach(() => {27 fs.readFileAsync.mockClear()28 fs.statAsync.mockClear()29 docgen.parse.mockClear()30 })31 it('should identify .js file (with extension)', async () => {32 // mocks33 fs.statAsync34 .mockImplementationOnce(jest.fn(async () => {35 const error = { errno: -2 }36 throw error37 }))38 .mockImplementationOnce(jest.fn(async () => {39 const error = { errno: -2 }40 throw error41 }))42 .mockImplementationOnce(jest.fn(async () => ({ isDirectory: () => false })))43 // calls44 await service.get()(...toRedux('/foo/bar/test.js'))45 // asserts46 expect(fs.readFileAsync.mock.calls.length).toBe(1)47 expect(fs.readFileAsync.mock.calls[0][0]).toBe('/foo/bar/test.js')48 expect(docgen.parse.mock.calls.length).toBe(1)49 expect(docgen.parse.mock.calls[0][1]).toEqual('componentResolver')50 })51 it('should resolve .js file (without extension)', async () => {52 // calls53 await service.get()(...toRedux('/foo/bar/test'))54 // asserts55 expect(fs.readFileAsync.mock.calls.length).toBe(1)56 expect(fs.readFileAsync.mock.calls[0][0]).toBe('/foo/bar/test.js')57 expect(docgen.parse.mock.calls.length).toBe(1)58 expect(docgen.parse.mock.calls[0][1]).toEqual('componentResolver')59 })60 it('should identify .jsx file (with extension)', async () => {61 // mocks62 fs.statAsync63 .mockImplementationOnce(jest.fn(async () => {64 const error = { errno: -2 }65 throw error66 }))67 .mockImplementationOnce(jest.fn(async () => {68 const error = { errno: -2 }69 throw error70 }))71 .mockImplementationOnce(jest.fn(async () => ({ isDirectory: () => false })))72 // calls73 await service.get()(...toRedux('/foo/bar/test.jsx'))74 // asserts75 expect(fs.readFileAsync.mock.calls.length).toBe(1)76 expect(fs.readFileAsync.mock.calls[0][0]).toBe('/foo/bar/test.jsx')77 expect(docgen.parse.mock.calls.length).toBe(1)78 expect(docgen.parse.mock.calls[0][1]).toEqual('componentResolver')79 })80 it('should resolve .jsx file (without extension)', async () => {81 // mocks82 fs.statAsync83 .mockImplementationOnce(jest.fn(async () => {84 const error = { errno: -2 }85 throw error86 }))87 .mockImplementationOnce(jest.fn(async () => ({ isDirectory: () => false })))88 // calls89 await service.get()(...toRedux('/foo/bar/test'))90 // asserts91 expect(fs.readFileAsync.mock.calls.length).toBe(1)92 expect(fs.readFileAsync.mock.calls[0][0]).toBe('/foo/bar/test.jsx')93 expect(docgen.parse.mock.calls.length).toBe(1)94 expect(docgen.parse.mock.calls[0][1]).toEqual('componentResolver')95 })96 it('should identify index file when a directory is given', async () => {97 // mocks98 fs.statAsync99 .mockImplementationOnce(jest.fn(async () => {100 const error = { errno: -2 }101 throw error102 }))103 .mockImplementationOnce(jest.fn(async () => {104 const error = { errno: -2 }105 throw error106 }))107 .mockImplementationOnce(jest.fn(async () => ({ isDirectory: () => true })))108 // calls109 await service.get()(...toRedux('/foo/bar/test'))110 // asserts111 expect(fs.readFileAsync.mock.calls.length).toBe(1)112 expect(fs.readFileAsync.mock.calls[0][0]).toBe('/foo/bar/test/index.js')113 expect(docgen.parse.mock.calls.length).toBe(1)114 expect(docgen.parse.mock.calls[0][1]).toEqual('indexResolver')115 })116 it('should resolve component in another file path when it is called', async () => {117 // mocks118 docgen.parse.mockImplementationOnce(jest.fn(() => {119 const error = { path: '/foo/bar/test/next' }120 throw error121 }))122 // calls123 await service.get()(...toRedux('/foo/bar/test'))124 // asserts125 expect(fs.readFileAsync.mock.calls.length).toBe(2)126 expect(fs.readFileAsync.mock.calls[0][0]).toBe('/foo/bar/test.js')127 expect(docgen.parse.mock.calls.length).toBe(2)128 expect(docgen.parse.mock.calls[0][1]).toEqual('componentResolver')129 expect(docgen.parse.mock.calls[1][1]).toEqual('componentResolver')130 })131 it('should resolve component in an index path when it is called', async () => {132 // mocks133 docgen.parse.mockImplementationOnce(jest.fn(() => {134 const error = { path: '/foo/bar/test/index' }135 throw error136 }))137 // calls138 await service.get()(...toRedux('/foo/bar/test/index'))139 // asserts140 expect(fs.readFileAsync.mock.calls.length).toBe(2)141 expect(fs.readFileAsync.mock.calls[0][0]).toBe('/foo/bar/test/index.js')142 })143 describe('errors', () => {144 it('should throw an error when unexpected fs error happens', async () => {145 // mocks146 docgen.parse.mockImplementationOnce(jest.fn(() => {147 throw new Error('unexpected')148 }))149 // calls150 let error = false151 try {152 await service.get()(...toRedux('/foo/bar/test'))153 } catch (ex) {154 error = true155 }156 // asserts157 expect(error).toBe(true)158 })159 it('should throw an error when unexpected fs error happens', async () => {160 // mocks161 fs.statAsync.mockImplementationOnce(jest.fn(() => {162 throw new Error('unexpected')163 }))164 // calls165 let error = false166 try {167 await service.get()(...toRedux('/foo/bar/test'))168 } catch (ex) {169 error = true170 }171 // asserts172 expect(error).toBe(true)173 })174 it('should return an exception when no filepath resolved', async () => {175 // mocks176 fs.statAsync177 .mockImplementationOnce(jest.fn(async () => ({ isDirectory: () => false })))178 .mockImplementation(jest.fn(async () => {179 const error = { errno: -2 }180 throw error181 }))182 // mocks183 docgen.parse.mockImplementationOnce(jest.fn(() => {184 const error = { path: '/foo/bar/test/index' }185 throw error186 }))187 // calls188 let error = false189 try {190 await service.get()(...toRedux('/foo/bar/test'))191 } catch (ex) {192 error = true193 }194 // asserts195 expect(error).toBe(true)196 })197 })...

Full Screen

Full Screen

fileSystem.js

Source:fileSystem.js Github

copy

Full Screen

1import * as BrowserFS from 'browserfs'2import folderPng from '../assets/folder.png'3import drivePng from '../assets/drive.png'4import Promise from 'bluebird'5import { sample } from 'lodash'6import {7 UPGRADES,8 EXTENSION_CONTENT,9 EXTENSION_IMAGES,10 INITIAL_DIRECTORIES,11 SPECIAL_FILE_NAMES,12} from '../constants'13export const fs = BrowserFS.BFSRequire('fs')14export const promiseFs = Promise.promisifyAll(fs)15export const path = BrowserFS.BFSRequire('path')16export const randomFs = function (config) {17 let promise = config.wipe ? rmdir(config.path) : Promise.resolve()18 return promise.then(function () {19 let promises = []20 for (let i = 0; i < config.number; i++) {21 try {22 const extension = sample(config.extensions) || 'txt'23 const filepath =24 path.resolve(25 process.cwd(),26 config.path,27 SPECIAL_FILE_NAMES[extension](),28 ) +29 '.' +30 extension31 EXTENSION_CONTENT[extension]((content) => {32 promises.push(addFile(filepath, content, 'utf8'))33 })34 } catch (e) {}35 }36 return Promise.all(promises)37 })38}39export const addFile = (filepath, content, format) => {40 mkdir(path.dirname(filepath)).then(() =>41 promiseFs.writeFileAsync(filepath, content, format),42 )43}44export const mkdir = (filepath) =>45 promiseFs.mkdirAsync(filepath).catch(function (e) {46 if (e.code === 'EEXIST' && e.errno === 17) return47 if (e.code === 'ENOENT' && e.errno === 2) {48 return mkdir(path.dirname(filepath)).then(() =>49 promiseFs.mkdirAsync(filepath),50 )51 }52 throw e53 })54export async function rmdir(filepath) {55 let files = []56 try {57 let fileStat = await promiseFs.statAsync(filepath)58 if (fileStat.isDirectory()) {59 files = await promiseFs.readdirAsync(filepath)60 for (let fileName of files) {61 let filePath = path.join(filepath, fileName)62 let fileStat = await promiseFs.statAsync(filePath)63 if (fileStat.isDirectory()) {64 await rmdir(filePath)65 } else {66 await promiseFs.unlinkAsync(filePath)67 }68 }69 await promiseFs.rmdirAsync(filepath)70 } else {71 await promiseFs.unlinkAsync(filepath)72 }73 } catch (e) {}74}75export async function getFileSizeForPath(directoryName, result = []) {76 let stat = await promiseFs.statAsync(directoryName)77 let files78 try {79 if (stat.isDirectory()) {80 files = await promiseFs.readdirAsync(directoryName)81 } else {82 result.push(stat.size)83 files = []84 }85 } catch (e) {}86 for (let f of files) {87 let fullPath = path.join(directoryName, f)88 let stat89 try {90 stat = await promiseFs.statAsync(fullPath)91 if (stat.isDirectory()) {92 await getFileSizeForPath(fullPath, result)93 } else {94 result.push(stat.size)95 }96 } catch (e) {}97 }98 return result.reduce((sum, n) => sum + n, 0) / 1024.099}100export async function getContentForPath(_file) {101 const stat = await promiseFs.statAsync(_file.path)102 if (!stat.isDirectory()) {103 return promiseFs.readFileAsync(_file.path).then((f) => {104 return f.toString()105 })106 }107 return promiseFs108 .readdirAsync(_file.path)109 .map((file) => {110 const fullPath = path.join(_file.path, file)111 return Promise.props({112 stat: promiseFs.statAsync(fullPath),113 accessLevel: getAccessLevel(fullPath),114 size: getFileSizeForPath(fullPath),115 path: fullPath,116 name: file,117 })118 })119 .all()120 .then((files) =>121 files.map((file) => {122 const isFolder = file.stat.isDirectory()123 const isDrive = file.path === '/C:'124 const extension = file.name.split('.')[1]125 return {126 ...file,127 type: isFolder ? 'folder' : 'file',128 isFolder,129 image: isDrive130 ? drivePng131 : isFolder132 ? folderPng133 : EXTENSION_IMAGES[extension],134 }135 }),136 )137}138BrowserFS.install(window)139BrowserFS.configure(140 {141 fs: 'LocalStorage',142 },143 async function (e) {144 if (e) {145 throw e146 }147 const hasFs = localStorage.getItem('has-fs')148 if (hasFs) return149 localStorage.setItem('has-fs', 'true')150 Object.entries(INITIAL_DIRECTORIES).forEach(([path, opts]) =>151 randomFs({ path, ...opts }),152 )153 },154)155export const getUpgrades = async () => {156 let upgrades = []157 try {158 upgrades = await promiseFs.readdirAsync(`/C:/Program Files`)159 } catch (e) {}160 let output = {}161 upgrades.forEach((u) => {162 const [key, level] = u.replace('.exe', '').split('_') || [0]163 output[key] = +level164 })165 UPGRADES.forEach((u) => {166 const currentUpgrade = upgrades.find((upgrade) => {167 const [key] = upgrade.replace('.exe', '').split('_')168 return key === u.key169 })170 let level = 0171 if (currentUpgrade) {172 level = currentUpgrade.replace('.exe', '').split('_')[1]173 }174 output[u.key] = level ? +level : 0175 })176 return output177}178const getAccessLevel = (path) => {179 const _path = path.replace(/\w+\.\w+/, '')180 const directory = INITIAL_DIRECTORIES[_path]181 if (directory && typeof directory.accessLevel === 'number')182 return directory.accessLevel183 return 0...

Full Screen

Full Screen

files.js

Source:files.js Github

copy

Full Screen

...10 .then((files) => {11 return Promise.reduce(files, (output, file) => {12 if(file==='__tagz' || file.startsWith('.')) return output;13 const absolutePath = Path.resolve(path);14 return fs.statAsync(Path.join(absolutePath, file))15 .then((stats) => {16 if(!stats.isDirectory()) {17 let myStats = _.pick(stats, 'size', 'birthtimeMs', 'mtimeMs');18 myStats.fileName = file;19 myStats.absolutePath = absolutePath;20 return tags.getTags(absolutePath, file)21 .then((tags) => {22 myStats.tags = tags || [];23 output.push(myStats);24 return output;25 });26 }27 return output;28 });29 }, []);30 })31 .catch((e) => {32 logger.error(e);33 })34}35module.exports.list = list;36const addTag = (path, tag) => {37 const fileName = Path.basename(path);38 if(fileName.startsWith('.'))39 throw new Error('Cannot add tag to hidden file');40 const absolutePath = Path.resolve(Path.dirname(path));41 return fs.statAsync(path)42 .then((stats) => {43 if(stats.isDirectory())44 throw new Error('Cannot add tag to directory');45 return [stats, tags.addTagToFile(Path.normalize(Path.dirname(path)), Path.basename(path), tag)];46 })47 .spread((stats, tags) => {48 let myStats = _.pick(stats, 'size', 'birthtimeMs', 'mtimeMs');49 myStats.fileName = fileName;50 myStats.absolutePath = absolutePath;51 myStats.tags = tags || [];52 return myStats;53 })54}55module.exports.addTag = addTag;56// const recursiveAddTag = (path, tag, directories, files) => {57// directories = directories || [];58// files = files || [];59// return fs.statAsync(path)60// .then((stats) => {61// if(!stats.isDirectory())62// throw new Error('Path must be a directory');63// return fs.readdirAsync(path);64// })65// .then((newFiles) => {66// newFiles.forEach((f) => {67// const fileWithPath = Path.join(path, f);68// if(fs.statSync(fileWithPath).isDirectory()) {69// directories.push(fileWithPath);70// } else {71// files.push(fileWithPath);72// }73// });74// if(directories.length > 0)75// return recursiveAddTag(directories.pop(), tag, directories, files);76// else77// return files;78// }).then((files) => {79// console.log(files);80// })81// }82const recursiveAddTag = (path, tag) => {83 const files = recursiveFileList(path)84 return Promise.reduce(files, (output, file) => {85 return addTag(file, tag)86 .then((stats) => {87 output.push(stats);88 return output;89 })90 }, [])91 .then((stats) => {92 return stats;93 });94}95module.exports.recursiveAddTag = recursiveAddTag;96const recursiveFileList = (path, directories, files) => {97 directories = directories || [];98 files = files || [];99 if(!fs.statSync(path).isDirectory())100 throw new Error('Path must be a directory');101 const newFiles = fs.readdirSync(path);102 newFiles.forEach((f) => {103 const fileWithPath = Path.join(path, f);104 if(fs.statSync(fileWithPath).isDirectory()) {105 directories.push(fileWithPath);106 } else {107 if(f !== '__tagz' && !f.startsWith('.'))108 files.push(fileWithPath);109 }110 });111 if(directories.length > 0)112 return recursiveFileList(directories.pop(), directories, files);113 else114 return files;115}116const removeTag = (path, tag) => {117 const fileName = Path.basename(path);118 if(fileName.startsWith('.'))119 throw new Error('Cannot remove tag from hidden file');120 const absolutePath = Path.resolve(Path.dirname(path));121 return fs.statAsync(path)122 .then((stats) => {123 if(stats.isDirectory())124 throw new Error('Cannot remove tag from directory');125 return [stats, tags.removeTagFromFile(Path.normalize(Path.dirname(path)), Path.basename(path), tag)];126 })127 .spread((stats, tags) => {128 let myStats = _.pick(stats, 'size', 'birthtimeMs', 'mtimeMs');129 myStats.fileName = fileName;130 myStats.absolutePath = absolutePath;131 myStats.tags = tags || [];132 return myStats;133 })134}135module.exports.removeTag = removeTag;...

Full Screen

Full Screen

test_device_mgmt_tool.js

Source:test_device_mgmt_tool.js Github

copy

Full Screen

...78 it('should rename upper dir and work dir, redis data, log data if restore function is called', (done) => {79 (async() =>{80 await gmt.resetDevice()81 try {82 await fs.statAsync(tempDir)83 assert.fail('temp dir should not exist');84 } catch (err) {85 expect(err).to.not.null;86 expect(err.code).to.equal('ENOENT');87 }88 try {89 await fs.statAsync(tempWorkDir)90 assert.fail('temp work dir should not exist');91 } catch (err) {92 expect(err).to.not.null;93 expect(err.code).to.equal('ENOENT');94 }95 try {96 await fs.statAsync(logFile1)97 assert.fail('log file 1 should not exist');98 } catch (err) {99 expect(err).to.not.null;100 expect(err.code).to.equal('ENOENT');101 }102 try {103 await fs.statAsync(logFile2)104 assert.fail('log file 2 should not exist');105 } catch (err) {106 expect(err).to.not.null;107 expect(err.code).to.equal('ENOENT');108 }109 try {110 await fs.statAsync(logDir1)111 await fs.statAsync(logDir2)112 } catch (err) {113 assert.fail('log dir1 and dir2 should exist');114 }115 try {116 let keys = await rclient.keysAsync("*")117 if(keys.length > 0)118 console.log(keys);119 expect(keys.length).to.equal(0); // all keys should be gone120 } catch (err) {121 assert.fail('should not cause error when querying redis');122 }123 done();124 })();125 });...

Full Screen

Full Screen

cli.compare-foo.mocha.man.js

Source:cli.compare-foo.mocha.man.js Github

copy

Full Screen

...37 .statAsync(p1)38 .then((stat1) => {39 p1Stat = stat1;40 })41 .then(() => fs.statAsync(p2))42 .then((stat2) => {43 expect(stat2.ino).toBe(p1Stat.ino);44 });45 });46 });47 });48 });49 describe('should not link non-matching files', () => {50 rootDirs.forEach((root) => {51 filesNotLinked.forEach((f) => {52 it(`${root}: ${f}`, () => {53 const p1 = Path.join(projectsPath, masterDir, f);54 const p2 = Path.join(projectsPath, root, f);55 let p1Stat;56 return fs57 .statAsync(p1)58 .then((stat1) => {59 p1Stat = stat1;60 })61 .then(() => fs.statAsync(p2))62 .then((stat2) => {63 expect(stat2.ino).toNotBe(p1Stat.ino);64 });65 });66 });67 });68 });...

Full Screen

Full Screen

bundler.test.js

Source:bundler.test.js Github

copy

Full Screen

1require("../setup");2var should = require("should"), assert = require("assert"), sinon = require("sinon"), repositories = require("../../data/repositories"), Promise = require("bluebird")3var fs = Promise.promisifyAll(require("fs"));4var sut = require("../../bundling/bundler");5describe("bundler", function() {6 describe("concatenate", function() {7 it("should read asset contents", function() {8 var assets = ["file1.js", "file2.js"];9 sinon.stub(fs, "readFileAsync");10 sinon.stub(fs, "statAsync").resolves({ isDirectory: function() { return false; } });11 return sut.concatenate(assets).then(function() {12 assert(fs.readFileAsync.calledWith("file1.js"));13 assert(fs.readFileAsync.calledWith("file2.js"));14 }).finally(function() {15 fs.readFileAsync.restore();16 fs.statAsync.restore();17 });18 });19 });20 describe("files", function() {21 it("should read directory files", function() {22 var assets = ["directory"];23 sinon.stub(fs, "readFileAsync");24 var stat = sinon.stub(fs, "statAsync");25 stat.withArgs("directory").resolves({ isDirectory: function() { return true; }});26 stat.withArgs("directory/file1.js").resolves({ isDirectory: function() { return false; }});27 stat.withArgs("directory/file2.js").resolves({ isDirectory: function() { return false; }});28 sinon.stub(fs, "readdirAsync").resolves(["file1.js", "file2.js"]);29 return sut.concatenate(assets).then(function() {30 assert(fs.readFileAsync.calledWith("directory/file1.js"));31 assert(fs.readFileAsync.calledWith("directory/file2.js"));32 }).finally(function() {33 fs.readFileAsync.restore();34 fs.statAsync.restore();35 fs.readdirAsync.restore();36 });37 });38 });...

Full Screen

Full Screen

test.js

Source:test.js Github

copy

Full Screen

...4// that has all its normal methods, and5// {methodName}Async method versions that return6// promises as well; ie, you will have a copy7// of fs with fs.stat(path, callback) and8// fs.statAsync(path), which returns a promise9// thus allowing us to await it.10const fs = bluebird.promisifyAll(require('fs'));11async function getFileSizeInKilobytes(path) {12 // Throwing inside of an async method causes the method13 // To return a rejected promise, which means we can throw based14 // On arguments15 if (!path) throw 'You must provide a path';16 const stats = await fs.statAsync(path);17 return stats.size / 1024;18}19async function main() {20 const kilos = await getFileSizeInKilobytes('./hello.txt');21 console.log(`That file is ${kilos}kb large!`);22}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const fs = require('fs');2const path = require('path');3const { promisify } = require('util');4const stat = promisify(fs.stat);5describe('Test', () => {6 it('should test', () => {7 cy.get('.action-upload > .fa').click();8 const filePath = path.join('..', 'fixtures', 'example.json');9 stat(filePath).then((file) => {10 cy.get('input[type="file"]').attachFile({11 });12 });13 });14});

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('test', () => {2 it('test', () => {3 cy.readFile('cypress/fixtures/test.txt').then((text) => {4 cy.writeFile('cypress/fixtures/test.txt', text)5 })6 })7})8describe('test', () => {9 it('test', () => {10 cy.readFile('cypress/fixtures/test.txt').then((text) => {11 cy.writeFile('cypress/fixtures/test.txt', text)12 })13 })14})15describe('test', () => {16 it('test', () => {17 cy.readFile('cypress/fixtures/test.txt').then((text) => {18 cy.writeFile('cypress/fixtures/test.txt', text)19 })20 })21})22describe('test', () => {23 it('test', () => {24 cy.readFile('cypress/fixtures/test.txt').then((text) => {25 cy.writeFile('cypress/fixtures/test.txt

Full Screen

Using AI Code Generation

copy

Full Screen

1const fs = require('fs-extra')2fs.statAsync('file.txt')3.then(stats => {4 if (stats.isFile()) {5 return fs.readFileAsync('file.txt', 'utf8')6 }7})8.then(contents => {9 return fs.writeFileAsync('file-copy.txt', contents)10})11.then(() => {12 return fs.renameAsync('file-copy.txt', 'file-renamed.txt')13})14.then(() => {15 console.log('done')16})17.catch(err => {18 console.error(err)19})

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful