How to use replaceFileContents method in Mocha

Best JavaScript code snippet using mocha

create.spec.js

Source:create.spec.js Github

copy

Full Screen

1/**2 Licensed to the Apache Software Foundation (ASF) under one3 or more contributor license agreements. See the NOTICE file4 distributed with this work for additional information5 regarding copyright ownership. The ASF licenses this file6 to you under the Apache License, Version 2.0 (the7 "License"); you may not use this file except in compliance8 with the License. You may obtain a copy of the License at9 http://www.apache.org/licenses/LICENSE-2.010 Unless required by applicable law or agreed to in writing,11 software distributed under the License is distributed on an12 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13 KIND, either express or implied. See the License for the14 specific language governing permissions and limitations15 under the License.16*/17var rewire = require('rewire');18var utils = require('../../lib/utils');19var create = rewire('../../lib/create');20var check_reqs = require('../../lib/check_reqs');21var fs = require('fs-extra');22var path = require('path');23describe('create', function () {24 describe('validatePackageName helper method', function () {25 describe('happy path (valid package names)', function () {26 var valid = [27 'org.apache.mobilespec',28 'com.example',29 'com.floors42.package',30 'ball8.ball8.ball8ball'31 ];32 valid.forEach(function (package_name) {33 it('Test#001 : should accept ' + package_name, () => {34 return create.validatePackageName(package_name);35 });36 });37 });38 describe('failure cases (invalid package names)', function () {39 function expectPackageNameToBeRejected (name) {40 return create.validatePackageName(name).then(() => {41 fail('Expected promise to be rejected');42 }, err => {43 expect(err).toEqual(jasmine.any(Error));44 expect(err.message).toContain('Error validating package name');45 });46 }47 it('should reject empty package names', () => {48 return expectPackageNameToBeRejected('');49 });50 it('should reject package names containing "class"', () => {51 return expectPackageNameToBeRejected('com.class.is.bad');52 });53 it('should reject package names that do not start with a latin letter', () => {54 return expectPackageNameToBeRejected('_un.der.score');55 });56 it('should reject package names with terms that do not start with a latin letter', () => {57 return expectPackageNameToBeRejected('un._der.score');58 });59 it('should reject package names containing non-alphanumeric or underscore characters', () => {60 return expectPackageNameToBeRejected('th!$.!$.b@d');61 });62 it('should reject package names that do not contain enough dots', () => {63 return expectPackageNameToBeRejected('therearenodotshere');64 });65 it('should reject package names that end with a dot', () => {66 return expectPackageNameToBeRejected('this.is.a.complete.sentence.');67 });68 });69 });70 describe('validateProjectName helper method', function () {71 describe('happy path (valid project names)', function () {72 var valid = [73 'mobilespec',74 'package_name',75 'PackageName',76 'CordovaLib',77 '1337',78 '3 Little Pigs',79 'CordovaActivity'80 ];81 valid.forEach(function (project_name) {82 it('Test#003 : should accept ' + project_name, () => {83 return create.validateProjectName(project_name);84 });85 });86 });87 describe('failure cases (invalid project names)', function () {88 it('should reject empty project names', () => {89 return create.validateProjectName('').then(() => {90 fail('Expected promise to be rejected');91 }, err => {92 expect(err).toEqual(jasmine.any(Error));93 expect(err.message).toContain('Project name cannot be empty');94 });95 });96 });97 });98 describe('main method', function () {99 var config_mock;100 var events_mock;101 var Manifest_mock = function () {};102 var revert_manifest_mock;103 var project_path = path.join('some', 'path');104 var app_path = path.join(project_path, 'app', 'src', 'main');105 var default_templates = path.join(__dirname, '..', '..', 'templates', 'project');106 var fake_android_target = 'android-1337';107 beforeEach(function () {108 Manifest_mock.prototype = jasmine.createSpyObj('AndroidManifest instance mock', ['setPackageId', 'getActivity', 'setName', 'write']);109 Manifest_mock.prototype.setPackageId.and.returnValue(new Manifest_mock());110 Manifest_mock.prototype.getActivity.and.returnValue(new Manifest_mock());111 Manifest_mock.prototype.setName.and.returnValue(new Manifest_mock());112 spyOn(create, 'validatePackageName').and.resolveTo();113 spyOn(create, 'validateProjectName').and.resolveTo();114 spyOn(create, 'copyJsAndLibrary');115 spyOn(create, 'copyScripts');116 spyOn(create, 'copyBuildRules');117 spyOn(create, 'writeProjectProperties');118 spyOn(create, 'prepBuildFiles');119 revert_manifest_mock = create.__set__('AndroidManifest', Manifest_mock);120 spyOn(fs, 'existsSync').and.returnValue(false);121 spyOn(fs, 'copySync');122 spyOn(fs, 'ensureDirSync');123 spyOn(utils, 'replaceFileContents');124 config_mock = jasmine.createSpyObj('ConfigParser mock instance', ['packageName', 'android_packageName', 'name', 'android_activityName']);125 events_mock = jasmine.createSpyObj('EventEmitter mock instance', ['emit']);126 spyOn(check_reqs, 'get_target').and.returnValue(fake_android_target);127 });128 afterEach(function () {129 revert_manifest_mock();130 });131 describe('parameter values and defaults', function () {132 it('should have a default package name of io.cordova.helloCordova', () => {133 config_mock.packageName.and.returnValue(undefined);134 return create.create(project_path, config_mock, {}, events_mock).then(() => {135 expect(create.validatePackageName).toHaveBeenCalledWith('io.cordova.helloCordova');136 });137 });138 it('should use the ConfigParser-provided package name, if exists', () => {139 config_mock.packageName.and.returnValue('org.apache.cordova');140 return create.create(project_path, config_mock, {}, events_mock).then(() => {141 expect(create.validatePackageName).toHaveBeenCalledWith('org.apache.cordova');142 });143 });144 it('should have a default project name of Hello Cordova', () => {145 config_mock.name.and.returnValue(undefined);146 return create.create(project_path, config_mock, {}, events_mock).then(() => {147 expect(create.validateProjectName).toHaveBeenCalledWith('Hello Cordova');148 });149 });150 it('should use the ConfigParser-provided project name, if exists', () => {151 config_mock.name.and.returnValue('MySweetAppName');152 return create.create(project_path, config_mock, {}, events_mock).then(() => {153 expect(create.validateProjectName).toHaveBeenCalledWith('MySweetAppName');154 });155 });156 it('should keep non-word characters (including unicode and spaces) in the ConfigParser-provided project name', () => {157 config_mock.name.and.returnValue('応応応応 hello 用用用用');158 return create.create(project_path, config_mock, {}, events_mock).then(() => {159 expect(create.validateProjectName).toHaveBeenCalledWith('応応応応 hello 用用用用');160 });161 });162 it('should have a default activity name of MainActivity', () => {163 config_mock.android_activityName.and.returnValue(undefined);164 return create.create(project_path, config_mock, {}, events_mock).then(() => {165 expect(Manifest_mock.prototype.setName).toHaveBeenCalledWith('MainActivity');166 });167 });168 it('should use the activityName provided via options parameter, if exists', () => {169 config_mock.android_activityName.and.returnValue(undefined);170 return create.create(project_path, config_mock, { activityName: 'AwesomeActivity' }, events_mock).then(() => {171 expect(Manifest_mock.prototype.setName).toHaveBeenCalledWith('AwesomeActivity');172 });173 });174 it('should use the ConfigParser-provided activity name, if exists', () => {175 config_mock.android_activityName.and.returnValue('AmazingActivity');176 return create.create(project_path, config_mock, {}, events_mock).then(() => {177 expect(Manifest_mock.prototype.setName).toHaveBeenCalledWith('AmazingActivity');178 });179 });180 });181 describe('failure', function () {182 it('should fail if the target path already exists', () => {183 fs.existsSync.and.returnValue(true);184 return create.create(project_path, config_mock, {}, events_mock).then(() => {185 fail('Expected promise to be rejected');186 }, err => {187 expect(err).toEqual(jasmine.any(Error));188 expect(err.message).toContain('Project already exists!');189 });190 });191 it('should fail if validateProjectName rejects', () => {192 const fakeError = new Error();193 create.validateProjectName.and.callFake(() => Promise.reject(fakeError));194 return create.create(project_path, config_mock, {}, events_mock).then(() => {195 fail('Expected promise to be rejected');196 }, err => {197 expect(err).toBe(fakeError);198 });199 });200 });201 describe('happy path', function () {202 it('should copy project templates from a specified custom template', () => {203 return create.create(project_path, config_mock, { customTemplate: '/template/path' }, events_mock).then(() => {204 expect(fs.copySync).toHaveBeenCalledWith(path.join('/template/path', 'assets'), path.join(app_path, 'assets'));205 expect(fs.copySync).toHaveBeenCalledWith(path.join('/template/path', 'res'), path.join(app_path, 'res'));206 expect(fs.copySync).toHaveBeenCalledWith(path.join('/template/path', 'gitignore'), path.join(project_path, '.gitignore'));207 });208 });209 it('should copy project templates from the default templates location if no custom template is provided', () => {210 return create.create(project_path, config_mock, {}, events_mock).then(() => {211 expect(fs.copySync).toHaveBeenCalledWith(path.join(default_templates, 'assets'), path.join(app_path, 'assets'));212 expect(fs.copySync).toHaveBeenCalledWith(path.join(default_templates, 'res'), path.join(app_path, 'res'));213 expect(fs.copySync).toHaveBeenCalledWith(path.join(default_templates, 'gitignore'), path.join(project_path, '.gitignore'));214 });215 });216 it('should copy JS and library assets', () => {217 return create.create(project_path, config_mock, {}, events_mock).then(() => {218 expect(create.copyJsAndLibrary).toHaveBeenCalled();219 });220 });221 it('should create a java src directory based on the provided project package name', () => {222 config_mock.packageName.and.returnValue('org.apache.cordova');223 return create.create(project_path, config_mock, {}, events_mock).then(() => {224 expect(fs.ensureDirSync).toHaveBeenCalledWith(path.join(app_path, 'java', 'org', 'apache', 'cordova'));225 });226 });227 it('should copy, rename and interpolate the template Activity java class with the project-specific activity name and package name', () => {228 config_mock.packageName.and.returnValue('org.apache.cordova');229 config_mock.android_activityName.and.returnValue('CEEDEEVEE');230 var activity_path = path.join(app_path, 'java', 'org', 'apache', 'cordova', 'CEEDEEVEE.java');231 return create.create(project_path, config_mock, {}, events_mock).then(() => {232 expect(fs.copySync).toHaveBeenCalledWith(path.join(default_templates, 'Activity.java'), activity_path);233 expect(utils.replaceFileContents).toHaveBeenCalledWith(activity_path, /__ACTIVITY__/, 'CEEDEEVEE');234 expect(utils.replaceFileContents).toHaveBeenCalledWith(activity_path, /__ID__/, 'org.apache.cordova');235 });236 });237 it('should interpolate the project name into strings.xml', () => {238 config_mock.name.and.returnValue('IncredibleApp');239 return create.create(project_path, config_mock, {}, events_mock).then(() => {240 expect(utils.replaceFileContents).toHaveBeenCalledWith(path.join(app_path, 'res', 'values', 'strings.xml'), /__NAME__/, 'IncredibleApp');241 });242 });243 it('should interpolate the escaped project name into strings.xml', () => {244 config_mock.name.and.returnValue('<Incredible&App>');245 return create.create(project_path, config_mock, {}, events_mock).then(() => {246 expect(utils.replaceFileContents).toHaveBeenCalledWith(path.join(app_path, 'res', 'values', 'strings.xml'), /__NAME__/, '&lt;Incredible&amp;App&gt;');247 });248 });249 it('should copy template scripts into generated project', () => {250 return create.create(project_path, config_mock, {}, events_mock).then(() => {251 expect(create.copyScripts).toHaveBeenCalledWith(project_path);252 });253 });254 it('should copy build rules / gradle files into generated project', () => {255 return create.create(project_path, config_mock, {}, events_mock).then(() => {256 expect(create.copyBuildRules).toHaveBeenCalledWith(project_path);257 });258 });259 it('should write project.properties file with project details and target API', () => {260 return create.create(project_path, config_mock, {}, events_mock).then(() => {261 expect(create.writeProjectProperties).toHaveBeenCalledWith(project_path, fake_android_target);262 });263 });264 it('should prepare build files', () => {265 return create.create(project_path, config_mock, {}, events_mock).then(() => {266 expect(create.prepBuildFiles).toHaveBeenCalledWith(project_path);267 });268 });269 });270 });...

Full Screen

Full Screen

create.js

Source:create.js Github

copy

Full Screen

...81 // `require` path for the two libraries. if there's a better way to share82 // modules across both the repo and generated projects, we should make sure83 // to remove/update this.84 const path_regex = /templates\/scripts\/cordova\//;85 utils.replaceFileContents(path.join(destScriptsDir, 'check_reqs'), path_regex, '');86 utils.replaceFileContents(path.join(destScriptsDir, 'apple_ios_version'), path_regex, '');87 utils.replaceFileContents(path.join(destScriptsDir, 'apple_osx_version'), path_regex, '');88 utils.replaceFileContents(path.join(destScriptsDir, 'apple_xcode_version'), path_regex, '');89 // CB-11792 do a token replace for __PROJECT_NAME__ in .xcconfig90 const project_name_esc = projectName.replace(/&/g, '\\&');91 utils.replaceFileContents(path.join(destScriptsDir, 'build-debug.xcconfig'), /__PROJECT_NAME__/g, project_name_esc);92 utils.replaceFileContents(path.join(destScriptsDir, 'build-release.xcconfig'), /__PROJECT_NAME__/g, project_name_esc);93}94/*95 * Copy project template files into cordova project.96 *97 * @param {String} project_path path to cordova project98 * @param {String} project_name name of cordova project99 * @param {String} project_template_dir path to cordova-ios template directory100 * @parm {BOOL} use_cli true if cli project101 */102function copyTemplateFiles (project_path, project_name, project_template_dir, package_name) {103 const r = path.join(project_path, project_name);104 fs.removeSync(path.join(`${r}.xcodeproj`));105 fs.copySync(path.join(project_template_dir, '__TEMP__.xcodeproj'), path.join(`${project_path}/__TEMP__.xcodeproj`));106 fs.moveSync(path.join(project_path, '__TEMP__.xcodeproj'), path.join(`${r}.xcodeproj`));107 fs.removeSync(path.join(project_path, `${project_name}.xcworkspace`));108 fs.copySync(path.join(project_template_dir, '__TEMP__.xcworkspace'), path.join(`${project_path}/__TEMP__.xcworkspace`));109 fs.moveSync(path.join(project_path, '__TEMP__.xcworkspace'), path.join(`${r}.xcworkspace`));110 fs.moveSync(path.join(`${r}.xcworkspace`, 'xcshareddata', 'xcschemes', '__PROJECT_NAME__.xcscheme'), path.join(`${r}.xcworkspace`, 'xcshareddata', 'xcschemes', `${project_name}.xcscheme`));111 fs.removeSync(r);112 fs.copySync(path.join(project_template_dir, '__PROJECT_NAME__'), path.join(`${project_path}/__PROJECT_NAME__`));113 fs.moveSync(path.join(project_path, '__PROJECT_NAME__'), r);114 fs.moveSync(path.join(r, '__PROJECT_NAME__-Info.plist'), path.join(r, `${project_name}-Info.plist`));115 fs.moveSync(path.join(r, '__PROJECT_NAME__-Prefix.pch'), path.join(r, `${project_name}-Prefix.pch`));116 fs.moveSync(path.join(r, 'gitignore'), path.join(r, '.gitignore'));117 /* replace __PROJECT_NAME__ and __PROJECT_ID__ with ACTIVITY and ID strings, respectively, in:118 *119 * - ./__PROJECT_NAME__.xcodeproj/project.pbxproj120 * - ./__PROJECT_NAME__/Classes/AppDelegate.h121 * - ./__PROJECT_NAME__/Classes/AppDelegate.m122 * - ./__PROJECT_NAME__/Classes/MainViewController.h123 * - ./__PROJECT_NAME__/Classes/MainViewController.m124 * - ./__PROJECT_NAME__/Resources/main.m125 * - ./__PROJECT_NAME__/Resources/__PROJECT_NAME__-info.plist126 * - ./__PROJECT_NAME__/Resources/__PROJECT_NAME__-Prefix.plist127 */128 // https://issues.apache.org/jira/browse/CB-12402 - Encode XML characters properly129 const project_name_xml_esc = xmlescape(project_name);130 utils.replaceFileContents(path.join(`${r}.xcworkspace`, 'contents.xcworkspacedata'), /__PROJECT_NAME__/g, project_name_xml_esc);131 utils.replaceFileContents(path.join(`${r}.xcworkspace`, 'xcshareddata', 'xcschemes', `${project_name}.xcscheme`), /__PROJECT_NAME__/g, project_name_xml_esc);132 const project_name_esc = project_name.replace(/&/g, '\\&');133 utils.replaceFileContents(path.join(`${r}.xcodeproj`, 'project.pbxproj'), /__PROJECT_NAME__/g, project_name_esc);134 utils.replaceFileContents(path.join(`${r}.xcodeproj`, 'project.pbxproj'), /__PROJECT_ID__/g, package_name);135 utils.replaceFileContents(path.join(r, 'Classes', 'AppDelegate.h'), /__PROJECT_NAME__/g, project_name_esc);136 utils.replaceFileContents(path.join(r, 'Classes', 'AppDelegate.m'), /__PROJECT_NAME__/g, project_name_esc);137 utils.replaceFileContents(path.join(r, 'Classes', 'MainViewController.h'), /__PROJECT_NAME__/g, project_name_esc);138 utils.replaceFileContents(path.join(r, 'Classes', 'MainViewController.m'), /__PROJECT_NAME__/g, project_name_esc);139 utils.replaceFileContents(path.join(r, 'main.m'), /__PROJECT_NAME__/g, project_name_esc);140 utils.replaceFileContents(path.join(r, `${project_name}-Info.plist`), /__PROJECT_NAME__/g, project_name_esc);141 utils.replaceFileContents(path.join(r, `${project_name}-Prefix.pch`), /__PROJECT_NAME__/g, project_name_esc);142}143function AbsParentPath (_path) {144 return path.resolve(path.dirname(_path));145}146function AbsProjectPath (relative_path) {147 let absolute_path = path.resolve(relative_path);148 if (/.pbxproj$/.test(absolute_path)) {149 absolute_path = AbsParentPath(absolute_path);150 } else if (!(/.xcodeproj$/.test(absolute_path))) {151 throw new Error(`The following is not a valid path to an Xcode project: ${absolute_path}`);152 }153 return absolute_path;154}155function relpath (_path, start) {156 start = start || process.cwd();157 return path.relative(path.resolve(start), path.resolve(_path));158}159/*160 * Creates a new iOS project with the following options:161 *162 * - --link (optional): Link directly against the shared copy of the CordovaLib instead of a copy of it163 * - --cli (optional): Use the CLI-project template164 * - <path_to_new_project>: Path to your new Cordova iOS project165 * - <package_name>: Package name, following reverse-domain style convention166 * - <project_name>: Project name167 * - <project_template_dir>: Path to a project template (override)168 *169 */170exports.createProject = (project_path, package_name, project_name, opts, config) => {171 package_name = package_name || 'my.cordova.project';172 project_name = project_name || 'CordovaExample';173 const use_shared = !!opts.link;174 const bin_dir = path.join(ROOT, 'bin');175 const project_parent = path.dirname(project_path);176 const project_template_dir = opts.customTemplate || path.join(bin_dir, 'templates', 'project');177 // check that project path doesn't exist178 if (fs.existsSync(project_path)) {179 return Promise.reject(new CordovaError('Project already exists'));180 }181 // check that parent directory does exist so cp -r will not fail182 if (!fs.existsSync(project_parent)) {183 return Promise.reject(new CordovaError(`Parent directory "${project_parent}" of given project path does not exist`));184 }185 events.emit('log', 'Creating Cordova project for the iOS platform:');186 events.emit('log', `\tPath: ${path.relative(process.cwd(), project_path)}`);187 events.emit('log', `\tPackage: ${package_name}`);188 events.emit('log', `\tName: ${project_name}`);189 events.emit('verbose', `Copying iOS template project to ${project_path}`);190 // create the project directory and copy over files191 fs.ensureDirSync(project_path);192 fs.copySync(path.join(project_template_dir, 'www'), path.join(project_path, 'www'));193 // Copy project template files194 copyTemplateFiles(project_path, project_name, project_template_dir, package_name);195 // Copy xcconfig files196 fs.copySync(path.join(project_template_dir, 'pods-debug.xcconfig'), path.join(project_path, 'pods-debug.xcconfig'));197 fs.copySync(path.join(project_template_dir, 'pods-release.xcconfig'), path.join(project_path, 'pods-release.xcconfig'));198 // CordovaLib stuff199 copyJsAndCordovaLib(project_path, project_name, use_shared, config);200 copyScripts(project_path, project_name);201 events.emit('log', generateDoneMessage('create', use_shared));202 return Promise.resolve();203};204exports.updateProject = (projectPath, opts) => {205 const errorString =206 'An in-place platform update is not supported. \n' +207 'The `platforms` folder is always treated as a build artifact.\n' +208 'To update your platform, you have to remove, then add your ios platform again.\n' +209 'Make sure you save your plugins beforehand using `cordova plugin save`, and save a copy of the platform first if you had manual changes in it.\n' +210 '\tcordova plugin save\n' +211 '\tcordova platform rm ios\n' +212 '\tcordova platform add ios\n';213 return Promise.reject(new CordovaError(errorString));214};215function generateDoneMessage (type, link) {216 const pkg = require('../../package');217 let msg = `iOS project ${type === 'update' ? 'updated' : 'created'} with ${pkg.name}@${pkg.version}`;218 if (link) {219 msg += ' and has a linked CordovaLib';220 }221 return msg;222}223function update_cordova_subproject (argv) {224 if (argv.length < 1 || argv.length > 3) {225 updateSubprojectHelp();226 throw new Error('Usage error for update_cordova_subproject');227 }228 const projectPath = AbsProjectPath(argv[0]);229 let cordovaLibXcodePath;230 if (argv.length < 3) {231 cordovaLibXcodePath = path.join(ROOT, 'CordovaLib', 'CordovaLib.xcodeproj');232 } else {233 cordovaLibXcodePath = AbsProjectPath(argv[1]);234 }235 const parentProjectPath = AbsParentPath(projectPath);236 const subprojectPath = relpath(cordovaLibXcodePath, parentProjectPath);237 const projectPbxprojPath = path.join(projectPath, 'project.pbxproj');238 const line = utils.grep(239 projectPbxprojPath,240 /(.+CordovaLib.xcodeproj.+PBXFileReference.+wrapper.pb-project.+)(path = .+?;)(.*)(sourceTree.+;)(.+)/241 );242 if (!line) {243 throw new Error(`Entry not found in project file for sub-project: ${subprojectPath}`);244 }245 let newLine = line246 .replace(/path = .+?;/, `path = ${subprojectPath};`)247 .replace(/sourceTree.+?;/, 'sourceTree = \"<group>\";'); /* eslint no-useless-escape : 0 */248 if (!newLine.match('name')) {249 newLine = newLine.replace('path = ', 'name = CordovaLib.xcodeproj; path = ');250 }251 utils.replaceFileContents(projectPbxprojPath, line, newLine);252}253exports.updateSubprojectHelp = updateSubprojectHelp;...

Full Screen

Full Screen

watch.spec.js

Source:watch.spec.js Github

copy

Full Screen

...41 });42 it('reruns test when watched test file crashes', function() {43 const testFile = path.join(tempDir, 'test.js');44 copyFixture(DEFAULT_FIXTURE, testFile);45 replaceFileContents(testFile, 'done();', 'done((;');46 return runMochaWatchJSONAsync([testFile], tempDir, () => {47 replaceFileContents(testFile, 'done((;', 'done();');48 }).then(results => {49 expect(results, 'to have length', 1);50 });51 });52 describe('when in parallel mode', function() {53 it('reruns test when watched test file is touched', function() {54 const testFile = path.join(tempDir, 'test.js');55 copyFixture(DEFAULT_FIXTURE, testFile);56 return runMochaWatchJSONAsync(['--parallel', testFile], tempDir, () => {57 touchFile(testFile);58 }).then(results => {59 expect(results, 'to have length', 2);60 });61 });62 it('reruns test when watched test file is crashed', function() {63 const testFile = path.join(tempDir, 'test.js');64 copyFixture(DEFAULT_FIXTURE, testFile);65 replaceFileContents(testFile, 'done();', 'done((;');66 return runMochaWatchJSONAsync([testFile], tempDir, () => {67 replaceFileContents(testFile, 'done((;', 'done();');68 }).then(results => {69 expect(results, 'to have length', 1);70 });71 });72 });73 it('reruns test when file matching --watch-files changes', function() {74 const testFile = path.join(tempDir, 'test.js');75 copyFixture(DEFAULT_FIXTURE, testFile);76 const watchedFile = path.join(tempDir, 'dir/file.xyz');77 touchFile(watchedFile);78 return runMochaWatchJSONAsync(79 [testFile, '--watch-files', 'dir/*.xyz'],80 tempDir,81 () => {82 touchFile(watchedFile);83 }84 ).then(results => {85 expect(results.length, 'to equal', 2);86 });87 });88 it('reruns test when file matching --watch-files is added', function() {89 const testFile = path.join(tempDir, 'test.js');90 copyFixture(DEFAULT_FIXTURE, testFile);91 const watchedFile = path.join(tempDir, 'lib/file.xyz');92 return runMochaWatchJSONAsync(93 [testFile, '--watch-files', '**/*.xyz'],94 tempDir,95 () => {96 touchFile(watchedFile);97 }98 ).then(results => {99 expect(results, 'to have length', 2);100 });101 });102 it('reruns test when file matching --watch-files is removed', function() {103 const testFile = path.join(tempDir, 'test.js');104 copyFixture(DEFAULT_FIXTURE, testFile);105 const watchedFile = path.join(tempDir, 'lib/file.xyz');106 touchFile(watchedFile);107 return runMochaWatchJSONAsync(108 [testFile, '--watch-files', 'lib/**/*.xyz'],109 tempDir,110 () => {111 fs.removeSync(watchedFile);112 }113 ).then(results => {114 expect(results, 'to have length', 2);115 });116 });117 it('does not rerun test when file not matching --watch-files is changed', function() {118 const testFile = path.join(tempDir, 'test.js');119 copyFixture(DEFAULT_FIXTURE, testFile);120 const watchedFile = path.join(tempDir, 'dir/file.js');121 touchFile(watchedFile);122 return runMochaWatchJSONAsync(123 [testFile, '--watch-files', 'dir/*.xyz'],124 tempDir,125 () => {126 touchFile(watchedFile);127 }128 ).then(results => {129 expect(results.length, 'to equal', 1);130 });131 });132 it('picks up new test files when they are added', function() {133 const testFile = path.join(tempDir, 'test/a.js');134 copyFixture(DEFAULT_FIXTURE, testFile);135 return runMochaWatchJSONAsync(136 ['test/**/*.js', '--watch-files', 'test/**/*.js'],137 tempDir,138 () => {139 const addedTestFile = path.join(tempDir, 'test/b.js');140 copyFixture('passing', addedTestFile);141 }142 ).then(results => {143 expect(results, 'to have length', 2);144 expect(results[0].passes, 'to have length', 1);145 expect(results[1].passes, 'to have length', 3);146 });147 });148 it('reruns test when file matching --extension is changed', function() {149 const testFile = path.join(tempDir, 'test.js');150 copyFixture(DEFAULT_FIXTURE, testFile);151 const watchedFile = path.join(tempDir, 'file.xyz');152 touchFile(watchedFile);153 return runMochaWatchJSONAsync(154 [testFile, '--extension', 'xyz,js'],155 tempDir,156 () => {157 touchFile(watchedFile);158 }159 ).then(results => {160 expect(results, 'to have length', 2);161 });162 });163 it('reruns when "rs\\n" typed', function() {164 const testFile = path.join(tempDir, 'test.js');165 copyFixture(DEFAULT_FIXTURE, testFile);166 return runMochaWatchJSONAsync([testFile], tempDir, mochaProcess => {167 mochaProcess.stdin.write('rs\n');168 }).then(results => {169 expect(results, 'to have length', 2);170 });171 });172 it('reruns test when file starting with . and matching --extension is changed', function() {173 const testFile = path.join(tempDir, 'test.js');174 copyFixture(DEFAULT_FIXTURE, testFile);175 const watchedFile = path.join(tempDir, '.file.xyz');176 touchFile(watchedFile);177 return runMochaWatchJSONAsync(178 [testFile, '--extension', 'xyz,js'],179 tempDir,180 () => {181 touchFile(watchedFile);182 }183 ).then(results => {184 expect(results, 'to have length', 2);185 });186 });187 it('ignores files in "node_modules" and ".git" by default', function() {188 const testFile = path.join(tempDir, 'test.js');189 copyFixture(DEFAULT_FIXTURE, testFile);190 const nodeModulesFile = path.join(tempDir, 'node_modules', 'file.xyz');191 const gitFile = path.join(tempDir, '.git', 'file.xyz');192 touchFile(gitFile);193 touchFile(nodeModulesFile);194 return runMochaWatchJSONAsync(195 [testFile, '--extension', 'xyz,js'],196 tempDir,197 () => {198 touchFile(gitFile);199 touchFile(nodeModulesFile);200 }201 ).then(results => {202 expect(results, 'to have length', 1);203 });204 });205 it('ignores files matching --watch-ignore', function() {206 const testFile = path.join(tempDir, 'test.js');207 copyFixture(DEFAULT_FIXTURE, testFile);208 const watchedFile = path.join(tempDir, 'dir/file-to-ignore.xyz');209 touchFile(watchedFile);210 return runMochaWatchJSONAsync(211 [212 testFile,213 '--watch-files',214 'dir/*.xyz',215 '--watch-ignore',216 'dir/*ignore*'217 ],218 tempDir,219 () => {220 touchFile(watchedFile);221 }222 ).then(results => {223 expect(results.length, 'to equal', 1);224 });225 });226 it('reloads test files when they change', function() {227 const testFile = path.join(tempDir, 'test.js');228 copyFixture('options/watch/test-file-change', testFile);229 return runMochaWatchJSONAsync(230 [testFile, '--watch-files', '**/*.js'],231 tempDir,232 () => {233 replaceFileContents(234 testFile,235 'testShouldFail = true',236 'testShouldFail = false'237 );238 }239 ).then(results => {240 expect(results, 'to have length', 2);241 expect(results[0].passes, 'to have length', 0);242 expect(results[0].failures, 'to have length', 1);243 expect(results[1].passes, 'to have length', 1);244 expect(results[1].failures, 'to have length', 0);245 });246 });247 it('reloads test dependencies when they change', function() {248 const testFile = path.join(tempDir, 'test.js');249 copyFixture('options/watch/test-with-dependency', testFile);250 const dependency = path.join(tempDir, 'lib', 'dependency.js');251 copyFixture('options/watch/dependency', dependency);252 return runMochaWatchJSONAsync(253 [testFile, '--watch-files', 'lib/**/*.js'],254 tempDir,255 () => {256 replaceFileContents(257 dependency,258 'module.exports.testShouldFail = false',259 'module.exports.testShouldFail = true'260 );261 }262 ).then(results => {263 expect(results, 'to have length', 2);264 expect(results[0].passes, 'to have length', 1);265 expect(results[0].failures, 'to have length', 0);266 expect(results[1].passes, 'to have length', 0);267 expect(results[1].failures, 'to have length', 1);268 });269 });270 // Regression test for https://github.com/mochajs/mocha/issues/2027271 it('respects --fgrep on re-runs', async function() {272 const testFile = path.join(tempDir, 'test.js');273 copyFixture('options/grep', testFile);274 return expect(275 runMochaWatchJSONAsync([testFile, '--fgrep', 'match'], tempDir, () => {276 touchFile(testFile);277 }),278 'when fulfilled',279 'to satisfy',280 {281 length: 2,282 0: {tests: expect.it('to have length', 2)},283 1: {tests: expect.it('to have length', 2)}284 }285 );286 });287 describe('with required hooks', function() {288 /**289 * Helper for setting up hook tests290 *291 * @param {string} hookName name of hook to test292 * @return {function}293 */294 function setupHookTest(hookName) {295 return function() {296 const testFile = path.join(tempDir, 'test.js');297 const hookFile = path.join(tempDir, 'hook.js');298 copyFixture('__default__', testFile);299 copyFixture('options/watch/hook', hookFile);300 replaceFileContents(hookFile, '<hook>', hookName);301 return runMochaWatchJSONAsync(302 [testFile, '--require', hookFile],303 tempDir,304 () => {305 touchFile(testFile);306 }307 ).then(results => {308 expect(results.length, 'to equal', 2);309 expect(results[0].failures, 'to have length', 1);310 expect(results[1].failures, 'to have length', 1);311 });312 };313 }314 it('mochaHooks.beforeAll runs as expected', setupHookTest('beforeAll'));...

Full Screen

Full Screen

main.js

Source:main.js Github

copy

Full Screen

1const fs = require("fs-extra");2const { exec } = require("child_process");3const readline = require("readline");4const path = require("path");5const config = require("./config.js");67(async () => {8 const profile = await promptProfileSelection(config.Profiles)9 .catch(err => {10 console.error(err);11 process.exit();12 });1314 if(profile.Backup) {15 console.log("Performing backup")16 await backupDashboard(profile.DashboardBasePath, config.DashboardBackupPath)17 .catch(err => {18 console.error("Failed to backup dashboard:", err);19 process.exit(1);20 });21 }2223 if(profile.PreModCommand) {24 console.log("Executing pre-mod command");25 await executeModCommand(profile.PreModCommand)26 .catch(err => {27 console.error("Failed to execute pre-mod command, skipping", err);28 });29 }3031 console.log("Executing find and replace");32 await findAndReplace(profile.FindAndReplace, profile.DashboardBasePath)33 .catch(err => {34 console.error("Failed to find and replace:", err);35 process.exit(1);36 });3738 console.log("Executing find and overwrite");39 await findAndOverwrite(profile.FindAndOverwrite, profile.DashboardBasePath, config.ModificationSourcePath)40 .catch(err => {41 console.error("Failed to find and overwrite:", err);42 process.exit(1);43 });4445 console.log("Executing find and insert");46 await findAndInsert(profile.FindAndInsert, profile.DashboardBasePath)47 .catch(err => {48 console.error("Failed to find and insert:", err);49 process.exit(1);50 });5152 if (profile.PostModCommand) {53 console.log("Executing post-mod command");54 await executeModCommand(profile.PostModCommand)55 .catch(err => {56 console.error("Failed to execute post-mod command", err);57 process.exit(1);58 });59 }6061 console.log("Successfully performed modifications without errors");62})();6364function executeModCommand(command) {65 return new Promise((resolve, reject) => {66 exec(command, (err, stdout, stderr) => {67 if(err) reject (err);68 if(stderr) reject(stderr);6970 resolve();71 })72 });73}7475function promptProfileSelection(profiles) {76 const interface = readline.createInterface({77 input: process.stdin,78 output: process.stdout79 });8081 profiles.push({ Name: "Exit Program" });8283 return new Promise((resolve, reject) => {84 interface.question(`Select a patch to apply:\n${profiles.map((p, i) => `${i}) ${p.Name}`).join("\n")} \n`, answer => {85 answer = Number(answer);8687 if(isNaN(answer)) return reject("Profile index must be a number")88 if(answer > (profiles.length - 1)) return reject(`No profile with the index ${answer} exists`);89 if(answer === (profiles.length - 1)) process.exit(0);9091 const profile = profiles[answer];9293 resolve(profile.Profile);9495 interface.close();96 });97 });98}99100function findAndReplace(replaceRules, basePath) {101 return new Promise(async (resolve, reject) => {102 for(const rule of replaceRules) {103 try {104 const destFilePath = path.join(basePath, rule.destFile);105106 const isDirDest = await fs.statSync(destFilePath).isDirectory();107 if(isDirDest) return reject(`Find and replace destination must be a file (${destFilePath})`);108109 let replaceFileContents = await fs.readFileSync(destFilePath, "utf8");110111 if(replaceFileContents.indexOf(rule.findString) === -1) reject(`Find string (${rule.findString}) not found in source (${destFilePath})`);112113 replaceFileContents = replaceFileContents.replace(rule.findString, rule.replaceString);114115 await fs.writeFileSync(destFilePath, replaceFileContents);116 } catch (err) {117 reject(err);118 }119 }120121 resolve();122 });123}124125function findAndInsert(insertRules, basePath) {126 return new Promise(async (resolve, reject) => {127 for (const rule of insertRules) {128 try {129 const destFilePath = path.join(basePath, rule.destFile);130131 const isDirDest = await fs.lstatSync(destFilePath).isDirectory();132 if(isDirDest) return reject(`Find and insert destination must be a file (${destFilePath})`);133134 let insertFileContents = await fs.readFileSync(destFilePath, "utf8");135 const insertIndex = insertFileContents.indexOf(rule.findString);136137 if(insertIndex === -1) return reject(`Find string (${rule.findString}) not found in source file (${destFilePath})`);138139 insertFileContents = insertAtIndex(insertFileContents, insertIndex + rule.findString.length, rule.insertString);140141 await fs.writeFileSync(destFilePath, insertFileContents);142 } catch (err) {143 reject(err);144 }145 }146147 resolve();148 });149}150151function findAndOverwrite(overwriteRules, basePath, modificationSourcePath) {152 return new Promise(async (resolve, reject) => {153 for (const rule of overwriteRules) {154 try {155 const sourcePath = path.join(modificationSourcePath, rule.source);156157 const isDir = await fs.statSync(sourcePath).isDirectory();158159 if(isDir) {160 await fs.copySync(sourcePath, path.join(basePath, rule.dest, path.parse(sourcePath).base), { overwrite: true });161 } else {162 await fs.copyFileSync(sourcePath, path.join(basePath, rule.dest, path.parse(sourcePath).base), { overwrite: true });163 } 164 } catch (err) {165 reject(err);166 }167 }168169 resolve();170 });171}172173function backupDashboard(sourcePath, destPath) {174 return new Promise((resolve, reject) => {175 fs.copy(sourcePath, path.join(destPath, "dashboard-ui-backup"), { overwrite: true }, (err) => {176 if(err) {177 reject(err);178 } else {179 resolve();180 }181 });182 });183}184 ...

Full Screen

Full Screen

utils.js

Source:utils.js Github

copy

Full Screen

...62 await openFile(filepath)63 await commands.executeCommand('workbench.action.files.save')64 return await sleep(1000) // Previous command file watcher won't have completed yet65}66function replaceFileContents(newText = '') {67 const editor = window.activeTextEditor68 return editor.edit((builder) => {69 builder.replace(editor.document.validateRange(new Range(0, 0, 9999999999, 0)), newText)70 })71}72function insertItem(item) {73 window.showQuickPick.callsFake(() => Promise.resolve(item))74 return commands.executeCommand('vandelay.selectImport')75}76async function insertItems(plugin, importItems) {77 for (const item of importItems) await insertItem(item)78 return window.activeTextEditor.document.getText()79}80async function insertTest(context, startingText, filepath, preserveFileContents) {81 const open = () => (filepath ? openFile(filepath) : openFile())82 const [plugin] = await Promise.all([getPlugin(), open()])83 if (!preserveFileContents) await replaceFileContents(startingText)84 let importItems = await buildImportItems()85 const originalResult = await insertItems(plugin, importItems)86 expect(originalResult).toMatchSnapshot(context, 'original order')87 if (process.env.FULL_INSERT_TEST) {88 for (let i = 0; i < 5; i++) {89 await replaceFileContents(startingText)90 importItems = _.shuffle(importItems)91 const newResult = await insertItems(plugin, importItems)92 if (newResult !== originalResult) {93 console.log(`\n\n${JSON.stringify(importItems)}\n\n`)94 }95 expect(newResult).toBe(originalResult)96 }97 }98}99async function insertDiffTest(context, startingText, filepath, preserveFileContents) {100 const open = () => (filepath ? openFile(filepath) : openFile())101 const [plugin] = await Promise.all([getPlugin(), open()])102 if (!preserveFileContents) await replaceFileContents(startingText)103 const importItems = await buildImportItems()104 const withContent = await insertItems(plugin, importItems)105 if (!this.withoutContent) {106 await replaceFileContents()107 this.withoutContent = await insertItems(plugin, importItems)108 }109 diff(context, this.withoutContent, withContent, {110 aAnnotation: 'Without Content',111 bAnnotation: 'With Content',112 contextLines: 2,113 })114}115async function configInsertDiffTest(context, file, config) {116 const [plugin] = await Promise.all([getPlugin(), openFile(file)])117 await replaceFileContents()118 if (!this.noConfig) {119 // Cache for faster test running120 const importItems = await buildImportItems()121 this.noConfig = await insertItems(plugin, importItems)122 await replaceFileContents()123 }124 Object.assign(plugin, config)125 const importItems = await buildImportItems()126 const withConfig = await insertItems(plugin, importItems)127 diff(context, this.noConfig, withConfig)128}129async function configInsertTest(context, config, reCache) {130 if (reCache) await commands.executeCommand('vandelay.cacheProject')131 const [plugin] = await Promise.all([getPlugin(), openFile()])132 await replaceFileContents()133 Object.assign(plugin, config)134 const importItems = await buildImportItems()135 const result = await insertItems(plugin, importItems)136 expect(result).toMatchSnapshot(context)137}138module.exports = {139 getPlugin,140 openFile,141 getExportData,142 testSpyCall,143 cacheTest,144 cacheDiffTest,145 buildImportItems,146 saveFile,...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...72 const fs = require("fs");73 74 const prettier = require("prettier");75 76 function replaceFileContents(file, replacements) {77 fs.writeFileSync(file, replacements);78 }79 80 let rawconfig = fs.readFileSync("config.json");81 let config = JSON.parse(rawconfig);82 config[object] = value83 let data = JSON.stringify(config, null, 2);84 let replace = replaceFileContents("config.json", data);85 console.log(JSON.parse(rawconfig));86 // console.log(config);87 88 })89// list configuration options90program91 // list configuration options92 .command("configurationList")93 .alias("cl")94 .description("List all of the configuration")95 .action(() => {96 const fs = require("fs");97 const prettier = require("prettier");98 let configuration = fs.readFileSync("config.json", "utf8");...

Full Screen

Full Screen

builders.js

Source:builders.js Github

copy

Full Screen

...44 file = file.replace(sassExtension, '.min.css');45 }46 const path = file.split('/');47 const fileName = path[path.length - 1];48 const withPaths = replaceFileContents(compiled);49 await fs.ensureDir(outPath);50 await fs.writeFile(join(outPath, fileName), withPaths);51 const t1 = performance.now();52 console.log(`${chalk.gray(fileName)} ${Math.round(t1 - t0)}ms`);53 }54};55/**56 * Compiles a string of data given its type.57 * @param {string} data58 * @param {'sass' | 'js' | 'html' | 'css' | 'file'} fileType59 * @returns {Promise<string>} The compiled data60 */61const compile = async (file, fileType) => {62 switch (fileType) {...

Full Screen

Full Screen

populate.js

Source:populate.js Github

copy

Full Screen

...51}52const populate = async () => {53 const names = ([...await readFileNames(), ...generatePaths()]).join('","');54 console.log(names);55 await replaceFileContents(/%URL%/g, `${names}`);56 await replaceFileContents(/%NAME%/g, `getpass-${+new Date}`);57}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const replaceFileContents = require('mocha/lib/utils').replaceFileContents;2const path = require('path');3const fs = require('fs');4const testFile = path.join(__dirname, 'test.js');5const content = fs.readFileSync(testFile, 'utf8');6replaceFileContents(testFile, content.replace('foo', 'bar'));7const replaceFileContents = require('mocha/lib/utils').replaceFileContents;8const path = require('path');9const fs = require('fs');10const testFile = path.join(__dirname, 'test.js');11const content = fs.readFileSync(testFile, 'utf8');12replaceFileContents(testFile, content.replace('foo', 'bar'));13const replaceFileContents = require('mocha/lib/utils').replaceFileContents;14const path = require('path');15const fs = require('fs');16const testFile = path.join(__dirname, 'test.js');17const content = fs.readFileSync(testFile, 'utf8');18replaceFileContents(testFile, content.replace('foo', 'bar'));19const replaceFileContents = require('mocha/lib/utils').replaceFileContents;20const path = require('path');21const fs = require('fs');22const testFile = path.join(__dirname, 'test.js');23const content = fs.readFileSync(testFile, 'utf8');24replaceFileContents(testFile, content.replace('foo', 'bar'));25const replaceFileContents = require('mocha/lib/utils').replaceFileContents;26const path = require('path');27const fs = require('fs');28const testFile = path.join(__dirname, 'test.js');29const content = fs.readFileSync(testFile, 'utf8');30replaceFileContents(testFile, content.replace('foo', 'bar'));31const replaceFileContents = require('mocha/lib/utils').replaceFileContents;32const path = require('path');33const fs = require('fs');34const testFile = path.join(__dirname, 'test.js');35const content = fs.readFileSync(testFile, 'utf8');36replaceFileContents(testFile, content.replace('foo', 'bar'));

Full Screen

Using AI Code Generation

copy

Full Screen

1const MochaFile = require('mocha-file');2let mochaFile = new MochaFile();3mochaFile.replaceFileContents('test.js', 'hello', 'world')4 .then(result => {5 console.log(result);6 })7 .catch(err => {8 console.log(err);9 });10const MochaFile = require('mocha-file');11let mochaFile = new MochaFile();12try {13 let result = mochaFile.replaceFileContentsSync('test.js', 'hello', 'world');14 console.log(result);15} catch (err) {16 console.log(err);17}18const MochaFile = require('mocha-file');19let mochaFile = new MochaFile();20mochaFile.appendFile('test.js', 'hello')21 .then(result => {22 console.log(result);23 })24 .catch(err => {25 console.log(err);26 });27const MochaFile = require('mocha-file');28let mochaFile = new MochaFile();29try {30 let result = mochaFile.appendFileSync('test.js', 'hello');31 console.log(result);32} catch (err) {33 console.log(err);34}

Full Screen

Using AI Code Generation

copy

Full Screen

1const fs = require('fs');2const path = require('path');3const Mocha = require('mocha');4const mocha = new Mocha();5const mochaReporters = require('mocha-reporters');6const junitReporter = new mochaReporters.JUnitXmlReporter({7});8mocha.addFile(path.join(__dirname, 'test.js'));9mocha.reporter(mochaReporters.JUnitXmlReporter, {10});11mocha.run(failures => {12 console.log('failures', failures);13 process.exitCode = failures ? -1 : 0;14 process.on('exit', function() {15 if (process.exitCode !== 0) {16 process.exit(1);17 }18 });19});20const replaceFileContents = (filePath, newContents) => {21 fs.writeFileSync(filePath, newContents);22};23const filePath = 'test-results/test-results.xml';24const contents = fs.readFileSync(filePath, 'utf8');25const newContents = contents.replace(/<testsuite/g, '<testsuite name="Mocha Tests"');26replaceFileContents(filePath, newContents);27const fs = require('fs');28const path = require('path');29const dir = 'test-results';30if (!fs.existsSync(dir)) {31 fs.mkdirSync(dir);32}33const fs = require('fs');34const path = require('path');35const dir = 'test-results';36if (!fs.existsSync(dir)) {37 fs.mkdirSync(dir);38}39const fs = require('fs');40const path = require('path');41const dir = 'test-results';42if (!fs.existsSync(dir)) {43 fs.mkdirSync(dir);44}45const fs = require('fs');46const path = require('path');47const dir = 'test-results';48if (!fs.existsSync(dir)) {49 fs.mkdirSync(dir);50}51const fs = require('fs');52const path = require('path');

Full Screen

Using AI Code Generation

copy

Full Screen

1const replaceFileContents = require('mocha/lib/utils').replaceFileContents;2replaceFileContents('test.js', /var mocha = new Mocha/, 'var mocha = new Mocha({ reporter: "dot" })');3replaceFileContents('test.js', /mocha.run/, 'mocha.run(function(failures) { process.on("exit", function () { process.exit(failures); }); });');4replaceFileContents('test.js', /mocha.reporter/, 'mocha.reporter("mochawesome");');5replaceFileContents('test.js', /mocha.run/, 'mocha.run(function(failures) { process.on("exit", function () { process.exit(failures); }); });');6replaceFileContents('test.js', /mocha.reporter/, 'mocha.reporter("mochawesome");');7replaceFileContents('test.js', /mocha.run/, 'mocha.run(function(failures) { process.on("exit", function () { process.exit(failures); }); });');8replaceFileContents('test.js', /mocha.reporter/, 'mocha.reporter("mochawesome");');9replaceFileContents('test.js', /mocha.run/, 'mocha.run(function(failures) { process.on("exit", function () { process.exit(failures); }); });');10replaceFileContents('test.js', /mocha.reporter/, 'mocha.reporter("mochawesome");');11replaceFileContents('test.js', /mocha.run/, 'mocha.run(function(failures) { process.on("exit", function () { process.exit(failures); }); });');12replaceFileContents('test.js', /mocha.reporter/, 'mocha.reporter("mochawesome");');

Full Screen

Using AI Code Generation

copy

Full Screen

1var MochaUtils = require('./MochaUtils.js');2var path = require('path');3var filePath = path.join(__dirname, 'test.html');4var replaceContents = "<h1>Test</h1>";5MochaUtils.replaceFileContents(filePath, replaceContents, function (err, data) {6 if (err) {7 console.log(err);8 }9 console.log(data);10});11var fs = require('fs');12module.exports = {13 replaceFileContents: function (filePath, replaceContents, callback) {14 fs.readFile(filePath, 'utf8', function (err, data) {15 if (err) {16 callback(err);17 } else {18 var result = data.replace(/<h1>.*<\/h1>/gm, replaceContents);19 callback(null, result);20 }21 });22 }23}

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mocha 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