Best JavaScript code snippet using mocha
release-nodetest.js
Source:release-nodetest.js
...15var EOL = require('os').EOL;16var RSVP = require('rsvp');17var rootPath = process.cwd();18var fixturePath = path.join(rootPath, 'tests/fixtures');19function copyFixture(name) {20 fs.copySync(path.join(fixturePath, name), '.');21}22describe("release command", function() {23 var ui, analytics, project, repo, npm;24 function fileExists(filePath) {25 return fs.existsSync(path.join(project.root, filePath));26 }27 function fileContents(filePath) {28 return fs.readFileSync(path.join(project.root, filePath), { encoding: 'utf8' });29 }30 beforeEach(function() {31 ui = new MockUI();32 analytics = new MockAnalytics();33 repo = new Mock(GitRepo);34 npm = new Mock(NPM);35 rimraf.sync('tmp');36 fs.mkdirSync('tmp');37 process.chdir('tmp');38 // Our tests copy config fixtures around, so we need to ensure39 // each test gets the current config/release.js result40 var configPath = path.resolve('config/release.js');41 if (require.cache[configPath]) {42 delete require.cache[configPath];43 }44 project = {45 root: path.resolve('.'),46 require: function(module) {47 if (module === 'ember-cli/lib/errors/silent') {48 return Error;49 } else {50 throw new Error('Module not found (fake implementation)');51 }52 },53 hasDependencies: function () {54 return true;55 },56 isEmberCLIProject: function(){57 return true;58 }59 };60 });61 afterEach(function() {62 process.chdir(rootPath);63 });64 function makeResponder(value) {65 return function() {66 return value;67 };68 }69 function createCommand(options) {70 options || (options = {});71 merge(options, {72 ui: ui,73 analytics: analytics,74 project: project,75 environment: {},76 settings: {},77 git: function() {78 return repo;79 },80 npm: function() {81 return npm;82 },83 });84 var TestReleaseCommand = Command.extend(ReleaseCommand);85 return new TestReleaseCommand(options);86 }87 describe("when HEAD is at a tag", function() {88 it("should exit immediately if HEAD is at a tag", function() {89 var cmd = createCommand();90 repo.respondTo('currentTag', makeResponder('v1.3.0'));91 return cmd.validateAndRun().catch(function(error) {92 expect(error.message).to.equals('Skipped tagging, HEAD already at tag: v1.3.0');93 });94 });95 });96 describe("when HEAD is not at a tag", function() {97 describe("when working copy has modifications", function() {98 beforeEach(function() {99 repo.respondTo('currentTag', makeResponder(null));100 });101 it("should warn of local changes and allow aborting", function() {102 var cmd = createCommand();103 ui.waitForPrompt().then(function() {104 ui.inputStream.write('n' + EOL);105 });106 repo.respondTo('tags', makeResponder([]));107 repo.respondTo('status', makeResponder(' M app/foo.js'));108 return cmd.validateAndRun([ '--local' ]).then(function() {109 expect(ui.output).to.contain("Your working tree contains modifications that will be added to the release commit, proceed?");110 }).catch(function(error) {111 expect(error.message).to.equals("Aborted.");112 });113 });114 it("should not warn or commit if only untracked files are present", function() {115 var cmd = createCommand();116 repo.respondTo('tags', makeResponder([]));117 repo.respondTo('status', makeResponder('?? not-in-repo.txt'));118 repo.respondTo('status', makeResponder('?? not-in-repo.txt'));119 repo.respondTo('createTag', makeResponder(null));120 return cmd.validateAndRun([ '--local', '--yes' ]).then(function() {121 expect(ui.output).to.not.contain("Your working tree contains modifications that will be added to the release commit, proceed?");122 });123 });124 });125 describe("when working copy has no modifications", function() {126 beforeEach(function() {127 repo.respondTo('currentTag', makeResponder(null));128 });129 describe("when repo has no existing tags", function() {130 var defaultTag = 'v0.1.0';131 beforeEach(function() {132 repo.respondTo('tags', makeResponder([]));133 repo.respondTo('status', makeResponder(''));134 repo.respondTo('status', makeResponder(''));135 });136 it("should create a default semver tag", function() {137 var createdTagName;138 var cmd = createCommand();139 ui.waitForPrompt().then(function() {140 ui.inputStream.write('y' + EOL);141 });142 repo.respondTo('createTag', function(tagName, message) {143 createdTagName = tagName;144 return null;145 });146 return cmd.validateAndRun([ '--local' ]).then(function() {147 expect(createdTagName).to.equal(defaultTag);148 expect(ui.output).to.contain("Successfully created git tag '" + defaultTag + "' locally.");149 });150 });151 });152 describe("when repo has existing tags", function() {153 var nextTag = 'v1.0.2';154 var tags = [155 {156 name: 'v1.0.0',157 sha: '7d1743e11a45f3863af1942b310412cbcd753271',158 date: new Date(Date.UTC(2013, 1, 15, 14, 35, 10))159 },160 {161 name: 'v1.0.1',162 sha: '0ace3a0a3a2c36acd44fc3acb2b0d57fde2faf6c',163 date: new Date(Date.UTC(2013, 2, 3, 4, 2, 33))164 }165 ];166 beforeEach(function() {167 repo.respondTo('tags', makeResponder(tags));168 repo.respondTo('status', makeResponder(''));169 });170 describe("when working copy is not changed", function() {171 beforeEach(function() {172 repo.respondTo('status', makeResponder(''));173 });174 describe("when an invalid semver tag exists", function() {175 var invalidTag = {176 name: 'v6.0.990.1',177 sha: '7a6d7bb7e5beb1bce2923dd6aea82f8a8e77438b',178 date: new Date(Date.UTC(2013, 1, 15, 15, 0, 0))179 };180 beforeEach(function() {181 tags.splice(1, 0, invalidTag);182 repo.respondTo('tags', makeResponder(tags));183 });184 it("should ignore invalid tags", function() {185 var cmd = createCommand();186 repo.respondTo('createTag', makeResponder(null));187 return cmd.validateAndRun([ '--local', '--yes' ]).then(function() {188 expect(ui.output).to.contain("Latest tag: " + tags[tags.length - 1].name);189 });190 });191 afterEach(function() {192 tags.splice(1, 1);193 });194 });195 it("should confirm tag creation and allow aborting", function() {196 var cmd = createCommand();197 ui.waitForPrompt().then(function() {198 ui.inputStream.write('n' + EOL);199 });200 return cmd.validateAndRun([ '--local' ]).then(function() {201 expect(ui.output).to.contain("About to create tag '" + nextTag + "', proceed?");202 }).catch(function(error) {203 expect(error.message).to.equals("Aborted.");204 });205 });206 it("should skip confirmation prompts when --yes option is set", function() {207 var cmd = createCommand();208 repo.respondTo('createTag', makeResponder(null));209 return cmd.validateAndRun([ '--local', '--yes' ]).then(function() {210 expect(ui.output).to.contain("Successfully created git tag '" + nextTag + "' locally.");211 });212 });213 it("should print the latest tag if returned by versioning strategy", function() {214 var cmd = createCommand();215 repo.respondTo('createTag', makeResponder(null));216 return cmd.validateAndRun([ '--local', '--yes' ]).then(function() {217 expect(ui.output).to.contain("Latest tag: " + tags[tags.length - 1].name);218 });219 });220 it("should replace the 'version' property in package.json and bower.json", function() {221 copyFixture('project-with-no-config');222 var cmd = createCommand();223 repo.respondTo('createTag', makeResponder(null));224 return cmd.validateAndRun([ '--local', '--yes' ]).then(function() {225 var pkg = JSON.parse(fs.readFileSync('./package.json'));226 var bower = JSON.parse(fs.readFileSync('./bower.json'));227 var rawVersion = nextTag.replace(/^v/, '');228 expect(pkg.version).to.equal(rawVersion);229 expect(bower.version).to.equal(rawVersion);230 });231 });232 it("should replace the 'version' property in the files specified by the 'manifest' option", function() {233 copyFixture('project-with-different-manifests');234 var cmd = createCommand();235 repo.respondTo('createTag', makeResponder(null));236 return cmd.validateAndRun([ '--local', '--yes', '--manifest=foo.json', '--manifest=bar.json' ]).then(function() {237 var foo = JSON.parse(fs.readFileSync('./foo.json'));238 var bar = JSON.parse(fs.readFileSync('./bar.json'));239 var rawVersion = nextTag.replace(/^v/, '');240 expect(foo.version).to.equal(rawVersion);241 expect(bar.version).to.equal(rawVersion);242 });243 });244 it("should not add a 'version' property in package.json and bower.json if it doesn't exsist", function() {245 copyFixture('project-with-no-versions');246 var cmd = createCommand();247 repo.respondTo('createTag', makeResponder(null));248 return cmd.validateAndRun([ '--local', '--yes' ]).then(function() {249 var pkg = JSON.parse(fs.readFileSync('./package.json'));250 var bower = JSON.parse(fs.readFileSync('./bower.json'));251 expect(pkg.version).to.be.undefined;252 expect(bower.version).to.be.undefined;253 });254 });255 it("should ensure package.json is normalized with a trailing newline", function() {256 copyFixture('project-with-config');257 var cmd = createCommand();258 repo.respondTo('createTag', makeResponder(null));259 return cmd.validateAndRun([ '--local', '--yes' ]).then(function() {260 var pkgSource = fs.readFileSync('./package.json', { encoding: 'utf8' });261 expect(pkgSource[pkgSource.length - 2]).to.equal('}');262 expect(pkgSource[pkgSource.length - 1]).to.equal('\n');263 });264 });265 it("should use the tag name specified by the --tag option", function() {266 var createdTagName, createdTagMessage;267 var cmd = createCommand();268 ui.waitForPrompt().then(function() {269 ui.inputStream.write('y' + EOL);270 });271 repo.respondTo('createTag', function(tagName, message) {272 createdTagName = tagName;273 createdTagMessage = message;274 return null;275 });276 return cmd.validateAndRun([ '--tag', 'foo', '--local' ]).then(function() {277 expect(createdTagName).to.equal('foo');278 expect(createdTagMessage).to.be.null;279 expect(ui.output).to.contain("Successfully created git tag '" + createdTagName + "' locally.");280 });281 });282 it("should use the message specified by the --annotation option", function() {283 var createdTagName, createdTagMessage;284 var cmd = createCommand();285 ui.waitForPrompt().then(function() {286 ui.inputStream.write('y' + EOL);287 });288 repo.respondTo('createTag', function(tagName, message) {289 createdTagName = tagName;290 createdTagMessage = message;291 return null;292 });293 return cmd.validateAndRun([ '--annotation', 'Tag %@', '--local' ]).then(function() {294 expect(createdTagName).to.equal(nextTag);295 expect(createdTagMessage ).to.equal('Tag ' + nextTag);296 expect(ui.output).to.contain("Successfully created git tag '" + createdTagName + "' locally.");297 });298 });299 it("should use the strategy specified by the --strategy option, passing tags and options", function() {300 var tagNames = tags.map(function(tag) { return tag.name; });301 var createdTagName, strategyTags, strategyOptions;302 var cmd = createCommand({303 strategies: function() {304 return {305 foo: {306 availableOptions: [307 {308 name: 'bar',309 type: Boolean,310 },311 {312 name: 'baz',313 type: String,314 },315 ],316 getNextTag: function(project, tags, options) {317 strategyTags = tags;318 strategyOptions = options;319 return 'foo';320 }321 }322 };323 }324 });325 ui.waitForPrompt().then(function() {326 ui.inputStream.write('y' + EOL);327 });328 repo.respondTo('createTag', function(tagName) {329 createdTagName = tagName;330 return null;331 });332 return cmd.validateAndRun([ '--strategy', 'foo', '--local', '--bar', '--baz', 'quux' ]).then(function() {333 expect(createdTagName).to.equal('foo');334 expect(strategyTags).to.deep.equal(tagNames);335 expect(strategyOptions.bar).to.be.true;336 expect(strategyOptions.baz).to.equal('quux');337 expect(ui.output).to.contain("Successfully created git tag '" + createdTagName + "' locally.");338 });339 });340 it("should push tags to the remote specified by the --remote option if the --local option is false", function() {341 var pushRemote, tagName;342 var cmd = createCommand();343 ui.waitForPrompt().then(function() {344 ui.inputStream.write('y' + EOL);345 });346 repo.respondTo('createTag', makeResponder(null));347 repo.respondTo('push', function(remote, tag) {348 pushRemote = remote;349 tagName = tag;350 return null;351 });352 return cmd.validateAndRun([ '--remote', 'foo' ]).then(function() {353 expect(pushRemote).to.equal('foo');354 expect(tagName).to.equal(nextTag);355 expect(ui.output).to.contain("About to create tag '" + nextTag + "' and push to remote '" + pushRemote + "', proceed?");356 expect(ui.output).to.contain("Successfully created git tag '" + nextTag + "' locally.");357 expect(ui.output).to.contain("Successfully pushed '" + nextTag + "' to remote '" + pushRemote + "'.");358 });359 });360 });361 describe("when publishing", function() {362 it("should abort if --local option is set", function() {363 var cmd = createCommand();364 return cmd.validateAndRun([ '--publish', '--local' ]).catch(function(error) {365 expect(error.message).to.equal("The --publish and --local options are incompatible.");366 });367 });368 it("should abort if --strategy option is not 'semver'", function() {369 var cmd = createCommand();370 return cmd.validateAndRun([ '--publish', '--strategy', 'date' ]).catch(function(error) {371 expect(error.message).to.equal("Publishing to NPM requires SemVer.");372 });373 });374 it("should abort if NPM user is not logged in", function() {375 var cmd = createCommand();376 npm.respondTo('whoami', function() {377 return RSVP.reject({378 code: 'ENEEDAUTH'379 });380 });381 return cmd.validateAndRun([ '--publish' ]).catch(function(error) {382 expect(error.message).to.equal("Must be logged in to perform NPM publish.");383 });384 });385 it("should print the NPM registry and user", function() {386 var cmd = createCommand();387 var username = 'foo';388 var registry = 'bar';389 npm.respondTo('whoami', makeResponder(username));390 npm.respondTo('config', function() {391 return {392 get: function(option) {393 return option === 'registry' ? registry : null;394 }395 };396 });397 repo.respondTo('status', makeResponder(''));398 ui.waitForPrompt().then(function() {399 ui.inputStream.write('n' + EOL);400 });401 return cmd.validateAndRun([ '--publish' ]).then(function() {402 expect(ui.output).to.equal("Using NPM registry " + registry + " as user '" + username + "'");403 }).catch(function() {});404 });405 it("should confirm publish and print package name/version", function() {406 copyFixture('project-with-no-config');407 var cmd = createCommand();408 var packageName = 'foo';409 var packageVersion = '1.0.2';410 npm.respondTo('whoami', makeResponder(''));411 npm.respondTo('config', function() {412 return {413 get: function() {}414 };415 });416 repo.respondTo('status', makeResponder(''));417 repo.respondTo('createTag', makeResponder(null));418 repo.respondTo('commitAll', makeResponder(null));419 repo.respondTo('push', makeResponder(null));420 ui.waitForPrompt().then(function() {421 ui.inputStream.write('y' + EOL);422 return ui.waitForPrompt();423 }).then(function() {424 ui.inputStream.write('n' + EOL);425 });426 return cmd.validateAndRun([ '--publish' ]).catch(function(error) {427 expect(ui.output).to.contain("About to publish " + packageName + "@" + packageVersion + ", proceed?");428 expect(error.message).to.equal("Aborted.");429 });430 });431 it("should publish to NPM using package.json at the project root", function() {432 copyFixture('project-with-no-config');433 var cmd = createCommand();434 var publishCalled = false;435 npm.respondTo('whoami', makeResponder(''));436 npm.respondTo('config', function() {437 return {438 get: function() {}439 };440 });441 repo.respondTo('status', makeResponder(''));442 repo.respondTo('createTag', makeResponder(null));443 repo.respondTo('commitAll', makeResponder(null));444 repo.respondTo('push', makeResponder(null));445 npm.respondTo('publish', function(args) {446 publishCalled = true;447 expect(args[0]).to.equal(project.root);448 });449 return cmd.validateAndRun([ '--publish', '--yes' ]).then(function() {450 expect(publishCalled).to.be.true;451 expect(ui.output).to.contain("Publish successful.");452 });453 });454 it("should publish if specified in config.js", function() {455 copyFixture('project-with-publish-config');456 var cmd = createCommand();457 var publishCalled = false;458 npm.respondTo('whoami', makeResponder(''));459 npm.respondTo('config', function() {460 return {461 get: function() {}462 };463 });464 repo.respondTo('status', makeResponder(''));465 repo.respondTo('createTag', makeResponder(null));466 repo.respondTo('commitAll', makeResponder(null));467 repo.respondTo('push', makeResponder(null));468 npm.respondTo('publish', function(args) {469 publishCalled = true;470 expect(args[0]).to.equal(project.root);471 });472 return cmd.validateAndRun([ '--yes' ]).then(function() {473 expect(publishCalled).to.be.true;474 expect(ui.output).to.contain("Publish successful.");475 });476 });477 it("should print the error if NPM publish failed", function() {478 copyFixture('project-with-no-config');479 var cmd = createCommand();480 npm.respondTo('whoami', makeResponder(''));481 npm.respondTo('config', function() {482 return {483 get: function() {}484 };485 });486 repo.respondTo('status', makeResponder(''));487 repo.respondTo('createTag', makeResponder(null));488 repo.respondTo('commitAll', makeResponder(null));489 repo.respondTo('push', makeResponder(null));490 npm.respondTo('publish', function() {491 return RSVP.reject(new Error('nope'));492 });493 return cmd.validateAndRun([ '--publish', '--yes' ]).catch(function(error) {494 expect(error.message).to.equal("nope");495 });496 });497 });498 describe("lifecycle hooks", function () {499 beforeEach(function() {500 repo.respondTo('currentBranch', makeResponder('master'));501 });502 it("should print a warning about non-function hooks", function() {503 copyFixture('project-with-bad-config');504 var cmd = createCommand();505 repo.respondTo('status', makeResponder(' M package.json'));506 repo.respondTo('createTag', makeResponder(null));507 repo.respondTo('commitAll', makeResponder(null));508 return cmd.validateAndRun([ '--local', '--yes' ]).then(function() {509 expect(ui.output).to.contain("Warning: `beforeCommit` is not a function");510 });511 });512 it("should execute hooks in the correct order", function () {513 copyFixture('project-with-hooks-config');514 var cmd = createCommand();515 var assertionCount = 0;516 expect(fileExists('init.txt'), 'init not called yet').to.be.false;517 repo.respondTo('status', function() {518 expect(fileExists('init.txt'), 'init called').to.be.true;519 assertionCount++;520 return ' M package.json';521 });522 repo.respondTo('commitAll', function() {523 expect(fileExists('before-commit.txt'), 'beforeCommit called').to.be.true;524 assertionCount++;525 });526 repo.respondTo('createTag', makeResponder(null));527 repo.respondTo('push', function() {528 expect(fileExists('after-push.txt'), 'afterPush not called yet').to.be.false;529 assertionCount++;530 });531 repo.respondTo('push', makeResponder(null));532 return cmd.validateAndRun([ '--yes' ]).then(function() {533 expect(fileExists('after-push.txt'), 'afterPush called').to.be.true;534 expect(fileExists('after-publish.txt'), 'afterPublish not called').to.be.false;535 expect(assertionCount, 'all assertions ran').to.equal(3);536 });537 });538 it("should call `afterPublish` hook when --publish option is set", function () {539 copyFixture('project-with-hooks-config');540 var cmd = createCommand();541 var assertionCount = 0;542 npm.respondTo('whoami', makeResponder(''));543 npm.respondTo('config', function() {544 return {545 get: function() {}546 };547 });548 repo.respondTo('status', makeResponder(''));549 repo.respondTo('createTag', makeResponder(null));550 repo.respondTo('push', makeResponder(null));551 npm.respondTo('publish', function() {552 expect(fileExists('after-push.txt'), 'afterPush called').to.be.true;553 expect(fileExists('after-publish.txt'), 'afterPublish not called yet').to.be.false;554 assertionCount++;555 });556 return cmd.validateAndRun([ '--publish', '--yes' ]).then(function() {557 expect(fileExists('after-publish.txt'), 'afterPublish called').to.be.true;558 expect(assertionCount, 'all assertions ran').to.equal(1);559 });560 });561 it("should pass the correct values into hooks", function () {562 copyFixture('project-with-hooks-config');563 var cmd = createCommand();564 repo.respondTo('status', makeResponder(' M package.json'));565 repo.respondTo('commitAll', makeResponder(null));566 repo.respondTo('createTag', makeResponder(null));567 repo.respondTo('push', makeResponder(null));568 repo.respondTo('push', makeResponder(null));569 return cmd.validateAndRun([ '--yes' ]).then(function() {570 expect(fileContents('init.txt')).to.equal(nextTag);571 expect(fileContents('before-commit.txt')).to.equal(nextTag);572 expect(fileContents('after-push.txt')).to.equal(nextTag);573 });574 });575 it("should allow aborting directly from hooks", function () {576 copyFixture('project-with-aborted-hooks-config');577 var cmd = createCommand();578 return cmd.validateAndRun([ '--tag', 'immediate' ]).catch(function(error) {579 expect(error.message).to.equals('Error encountered in `init` hook: "nope"');580 });581 });582 it("should allow aborting from promise returned by hooks", function () {583 copyFixture('project-with-aborted-hooks-config');584 var cmd = createCommand();585 return cmd.validateAndRun([ '--tag', 'promise' ]).catch(function(error) {586 expect(error.message).to.equals('Error encountered in `init` hook: "nope"');587 });588 });589 });590 describe("configuration via config/release.js", function () {591 beforeEach(function() {592 repo.respondTo('status', makeResponder(''));593 });594 it("should print a warning about unknown options", function() {595 copyFixture('project-with-bad-config');596 var cmd = createCommand();597 repo.respondTo('createTag', makeResponder(null));598 return cmd.validateAndRun([ '--local', '--yes' ]).then(function() {599 expect(ui.output).to.contain("Warning: cannot specify option `minor`");600 expect(ui.output).to.contain("Warning: invalid option `foo`");601 });602 });603 it("should allow flexible option values", function() {604 copyFixture('project-with-bad-config');605 var cmd = createCommand();606 repo.respondTo('createTag', makeResponder(null));607 // This tests that the `manifest` option can be specified as a single string608 return cmd.validateAndRun([ '--local', '--yes' ]).then(function() {609 var foo = JSON.parse(fs.readFileSync('./foo.json'));610 var rawVersion = nextTag.replace(/^v/, '');611 expect(foo.version).to.equal(rawVersion);612 });613 });614 it("should use the strategy specified by the config file", function() {615 var createdTagName;616 copyFixture('project-with-config');617 var cmd = createCommand();618 repo.respondTo('createTag', function(tagName) {619 createdTagName = tagName;620 return null;621 });622 return cmd.validateAndRun([ '--local', '--yes' ]).then(function() {623 expect(createdTagName).to.match(/\d{4}\.\d{2}\.\d{2}/);624 expect(ui.output).to.contain("Successfully created git tag '" + createdTagName + "' locally.");625 });626 });627 it("should use the strategy specified on the command line over one in the config file", function() {628 var createdTagName;629 copyFixture('project-with-config');630 var cmd = createCommand();631 repo.respondTo('createTag', function(tagName) {632 createdTagName = tagName;633 return null;634 });635 return cmd.validateAndRun([ '--strategy', 'semver', '--local', '--yes' ]).then(function() {636 expect(createdTagName).to.equal(nextTag);637 expect(ui.output).to.contain("Successfully created git tag '" + createdTagName + "' locally.");638 });639 });640 it("should use the strategy defined in the config file", function() {641 var tagNames = tags.map(function(tag) { return tag.name; });642 var tagName = 'foo';643 copyFixture('project-with-strategy-config');644 var cmd = createCommand();645 repo.respondTo('createTag', makeResponder(null));646 return cmd.validateAndRun([ '--local', '--yes' ]).then(function() {647 expect(JSON.parse(fileContents('tags.json'))).to.deep.equal(tagNames);648 expect(ui.output).to.contain("Successfully created git tag '" + tagName + "' locally.");649 });650 });651 it("should use the strategy and options defined in the config file", function() {652 var tagName = 'foo';653 copyFixture('project-with-options-strategy-config');654 var cmd = createCommand();655 repo.respondTo('createTag', makeResponder(null));656 return cmd.validateAndRun([ '--local', '--yes', '--foo', 'bar' ]).then(function() {657 expect(JSON.parse(fileContents('options.json'))).to.have.property('foo', 'bar');658 expect(ui.output).to.contain("Successfully created git tag '" + tagName + "' locally.");659 });660 });661 it("should abort if the strategy defined in the config file does not return a valid value", function() {662 var tagNames = tags.map(function(tag) { return tag.name; });663 var tagName = 'foo';664 copyFixture('project-with-bad-strategy-config');665 var cmd = createCommand();666 repo.respondTo('createTag', makeResponder(null));667 return cmd.validateAndRun([ '--local', '--yes' ]).catch(function(error) {668 expect(error.message).to.equal("Tagging strategy must return a non-empty tag name");669 });670 });671 });672 describe("when working copy is changed", function() {673 beforeEach(function() {674 repo.respondTo('status', makeResponder('M package.json'));675 });676 describe("when repo is in detached HEAD state", function() {677 beforeEach(function() {678 repo.respondTo('currentBranch', makeResponder(null));...
watch.spec.js
Source:watch.spec.js
...16 }17 });18 it('reruns test when watched test file is touched', function() {19 const testFile = path.join(this.tempDir, 'test.js');20 copyFixture('__default__', testFile);21 return runMochaWatch([testFile], this.tempDir, () => {22 touchFile(testFile);23 }).then(results => {24 expect(results, 'to have length', 2);25 });26 });27 it('reruns test when file matching --watch-files changes', function() {28 const testFile = path.join(this.tempDir, 'test.js');29 copyFixture('__default__', testFile);30 const watchedFile = path.join(this.tempDir, 'dir/file.xyz');31 touchFile(watchedFile);32 return runMochaWatch(33 [testFile, '--watch-files', 'dir/*.xyz'],34 this.tempDir,35 () => {36 touchFile(watchedFile);37 }38 ).then(results => {39 expect(results.length, 'to equal', 2);40 });41 });42 it('reruns test when file matching --watch-files is added', function() {43 const testFile = path.join(this.tempDir, 'test.js');44 copyFixture('__default__', testFile);45 const watchedFile = path.join(this.tempDir, 'lib/file.xyz');46 return runMochaWatch(47 [testFile, '--watch-files', '**/*.xyz'],48 this.tempDir,49 () => {50 touchFile(watchedFile);51 }52 ).then(results => {53 expect(results, 'to have length', 2);54 });55 });56 it('reruns test when file matching --watch-files is removed', function() {57 const testFile = path.join(this.tempDir, 'test.js');58 copyFixture('__default__', testFile);59 const watchedFile = path.join(this.tempDir, 'lib/file.xyz');60 touchFile(watchedFile);61 return runMochaWatch(62 [testFile, '--watch-files', 'lib/**/*.xyz'],63 this.tempDir,64 () => {65 fs.removeSync(watchedFile);66 }67 ).then(results => {68 expect(results, 'to have length', 2);69 });70 });71 it('does not rerun test when file not matching --watch-files is changed', function() {72 const testFile = path.join(this.tempDir, 'test.js');73 copyFixture('__default__', testFile);74 const watchedFile = path.join(this.tempDir, 'dir/file.js');75 touchFile(watchedFile);76 return runMochaWatch(77 [testFile, '--watch-files', 'dir/*.xyz'],78 this.tempDir,79 () => {80 touchFile(watchedFile);81 }82 ).then(results => {83 expect(results.length, 'to equal', 1);84 });85 });86 it('picks up new test files when they are added', function() {87 const testFile = path.join(this.tempDir, 'test/a.js');88 copyFixture('__default__', testFile);89 return runMochaWatch(90 ['test/**/*.js', '--watch-files', 'test/**/*.js'],91 this.tempDir,92 () => {93 const addedTestFile = path.join(this.tempDir, 'test/b.js');94 copyFixture('passing', addedTestFile);95 }96 ).then(results => {97 expect(results, 'to have length', 2);98 expect(results[0].passes, 'to have length', 1);99 expect(results[1].passes, 'to have length', 3);100 });101 });102 it('reruns test when file matching --extension is changed', function() {103 const testFile = path.join(this.tempDir, 'test.js');104 copyFixture('__default__', testFile);105 const watchedFile = path.join(this.tempDir, 'file.xyz');106 touchFile(watchedFile);107 return runMochaWatch(108 [testFile, '--extension', 'xyz,js'],109 this.tempDir,110 () => {111 touchFile(watchedFile);112 }113 ).then(results => {114 expect(results, 'to have length', 2);115 });116 });117 it('reruns test when file starting with . and matching --extension is changed', function() {118 const testFile = path.join(this.tempDir, 'test.js');119 copyFixture('__default__', testFile);120 const watchedFile = path.join(this.tempDir, '.file.xyz');121 touchFile(watchedFile);122 return runMochaWatch(123 [testFile, '--extension', 'xyz,js'],124 this.tempDir,125 () => {126 touchFile(watchedFile);127 }128 ).then(results => {129 expect(results, 'to have length', 2);130 });131 });132 it('ignores files in "node_modules" and ".git" by default', function() {133 const testFile = path.join(this.tempDir, 'test.js');134 copyFixture('__default__', testFile);135 const nodeModulesFile = path.join(136 this.tempDir,137 'node_modules',138 'file.xyz'139 );140 const gitFile = path.join(this.tempDir, '.git', 'file.xyz');141 touchFile(gitFile);142 touchFile(nodeModulesFile);143 return runMochaWatch(144 [testFile, '--extension', 'xyz,js'],145 this.tempDir,146 () => {147 touchFile(gitFile);148 touchFile(nodeModulesFile);149 }150 ).then(results => {151 expect(results, 'to have length', 1);152 });153 });154 it('ignores files matching --watch-ignore', function() {155 const testFile = path.join(this.tempDir, 'test.js');156 copyFixture('__default__', testFile);157 const watchedFile = path.join(this.tempDir, 'dir/file-to-ignore.xyz');158 touchFile(watchedFile);159 return runMochaWatch(160 [161 testFile,162 '--watch-files',163 'dir/*.xyz',164 '--watch-ignore',165 'dir/*ignore*'166 ],167 this.tempDir,168 () => {169 touchFile(watchedFile);170 }171 ).then(results => {172 expect(results.length, 'to equal', 1);173 });174 });175 it('reloads test files when they change', function() {176 const testFile = path.join(this.tempDir, 'test.js');177 copyFixture('options/watch/test-file-change', testFile);178 return runMochaWatch(179 [testFile, '--watch-files', '**/*.js'],180 this.tempDir,181 () => {182 replaceFileContents(183 testFile,184 'testShouldFail = true',185 'testShouldFail = false'186 );187 }188 ).then(results => {189 expect(results, 'to have length', 2);190 expect(results[0].passes, 'to have length', 0);191 expect(results[0].failures, 'to have length', 1);192 expect(results[1].passes, 'to have length', 1);193 expect(results[1].failures, 'to have length', 0);194 });195 });196 it('reloads test dependencies when they change', function() {197 const testFile = path.join(this.tempDir, 'test.js');198 copyFixture('options/watch/test-with-dependency', testFile);199 const dependency = path.join(this.tempDir, 'lib', 'dependency.js');200 copyFixture('options/watch/dependency', dependency);201 return runMochaWatch(202 [testFile, '--watch-files', 'lib/**/*.js'],203 this.tempDir,204 () => {205 replaceFileContents(206 dependency,207 'module.exports.testShouldFail = false',208 'module.exports.testShouldFail = true'209 );210 }211 ).then(results => {212 expect(results, 'to have length', 2);213 expect(results[0].passes, 'to have length', 1);214 expect(results[0].failures, 'to have length', 0);215 expect(results[1].passes, 'to have length', 0);216 expect(results[1].failures, 'to have length', 1);217 });218 });219 // Regression test for https://github.com/mochajs/mocha/issues/2027220 it('respects --fgrep on re-runs', function() {221 const testFile = path.join(this.tempDir, 'test.js');222 copyFixture('options/grep', testFile);223 return runMochaWatch([testFile, '--fgrep', 'match'], this.tempDir, () => {224 touchFile(testFile);225 }).then(results => {226 expect(results, 'to have length', 2);227 expect(results[0].tests, 'to have length', 2);228 expect(results[1].tests, 'to have length', 2);229 });230 });231 });232});233/**234 * Runs the mocha binary in watch mode calls `change` and returns the235 * JSON reporter output.236 *237 * The function starts mocha with the given arguments and `--watch` and238 * waits until the first test run has completed. Then it calls `change`239 * and waits until the second test run has been completed. Mocha is240 * killed and the list of JSON outputs is returned.241 */242function runMochaWatch(args, cwd, change) {243 const [mochaProcess, resultPromise] = helpers.invokeMochaAsync(244 [...args, '--watch', '--reporter', 'json'],245 {cwd}246 );247 return sleep(1000)248 .then(() => change())249 .then(() => sleep(1000))250 .then(() => {251 mochaProcess.kill('SIGINT');252 return resultPromise;253 })254 .then(data => {255 const testResults = data.output256 // eslint-disable-next-line no-control-regex257 .replace(/\u001b\[\?25./g, '')258 .split('\u001b[2K')259 .map(x => JSON.parse(x));260 return testResults;261 });262}263/**264 * Synchronously touch a file by appending a space to the end. Creates265 * the file and all its parent directories if necessary.266 */267function touchFile(file) {268 fs.ensureDirSync(path.dirname(file));269 fs.appendFileSync(file, ' ');270}271/**272 * Synchronously replace all substrings matched by `pattern` with273 * `replacement` in the fileâs content.274 */275function replaceFileContents(file, pattern, replacement) {276 const contents = fs.readFileSync(file, 'utf-8');277 const newContents = contents.replace(pattern, replacement);278 fs.writeFileSync(file, newContents, 'utf-8');279}280/**281 * Synchronously copy a fixture to the given destination file path.282 * Creates parent directories of the destination path if necessary.283 */284function copyFixture(fixtureName, dest) {285 const fixtureSource = helpers.resolveFixturePath(fixtureName);286 fs.ensureDirSync(path.dirname(dest));287 fs.copySync(fixtureSource, dest);288}289function sleep(time) {290 return new Promise(resolve => {291 setTimeout(resolve, time);292 });...
fixtures.js
Source:fixtures.js
...11 * nuclide-test-helpers package directory that should be copied. Must contain a .hg-rename folder.12 * @returns the path to the temporary directory that this function creates.13 */14var copyMercurialFixture = _asyncToGenerator(function* (fixtureName) {15 var repo = yield (_nuclideTestHelpers2 || _nuclideTestHelpers()).fixtures.copyFixture(fixtureName, getTestDir());16 var pathToHg = (_nuclideRemoteUri2 || _nuclideRemoteUri()).default.join(repo, '.hg-rename');17 (0, (_assert2 || _assert()).default)((0, (_fsPlus2 || _fsPlus()).existsSync)(pathToHg), 'Directory: ' + pathToHg + ' was not found.');18 (0, (_fsPlus2 || _fsPlus()).moveSync)(pathToHg, (_nuclideRemoteUri2 || _nuclideRemoteUri()).default.join(repo, '.hg'));19 return (0, (_fsPlus2 || _fsPlus()).absolute)(repo);20}21/**22 * Set the project. If there are one or more projects set previously, this replaces them all with23 * the one(s) provided as the argument `projectPath`.24 */25);26exports.copyMercurialFixture = copyMercurialFixture;27exports.setLocalProject = setLocalProject;28/*29 * Copies a specified subdirectory of spec/fixtures to a temporary location.30 *31 * @param fixtureName The name of the subdirectory of the fixtures/ directory within the32 * nuclide-test-helpers package directory that should be copied.33 * @returns the path to the temporary directory that this function creates.34 */35var copyFixture = _asyncToGenerator(function* (fixtureName) {36 var fixturePath = yield (_nuclideTestHelpers2 || _nuclideTestHelpers()).fixtures.copyFixture(fixtureName, getTestDir());37 return (0, (_fsPlus2 || _fsPlus()).absolute)(fixturePath);38});39exports.copyFixture = copyFixture;40function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { var callNext = step.bind(null, 'next'); var callThrow = step.bind(null, 'throw'); function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(callNext, callThrow); } } callNext(); }); }; }41function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }42/*43 * Copyright (c) 2015-present, Facebook, Inc.44 * All rights reserved.45 *46 * This source code is licensed under the license found in the LICENSE file in47 * the root directory of this source tree.48 */49var _assert2;50function _assert() {...
optionalCatchAll_spec.js
Source:optionalCatchAll_spec.js
1const project = "optionalCatchAll";2before(() => {3 // When changing the base URL within a spec file, Cypress runs the spec twice4 // To avoid rebuilding and redeployment on the second run, we check if the5 // project has already been deployed.6 cy.task("isDeployed").then((isDeployed) => {7 // Cancel setup, if already deployed8 if (isDeployed) return;9 // Clear project folder10 cy.task("clearProject", { project });11 // Copy NextJS files12 cy.task("copyFixture", {13 project,14 from: "pages-with-optionalCatchAll",15 to: "pages",16 });17 cy.task("copyFixture", {18 project,19 from: "next.config.js-with-optionalCatchAll",20 to: "next.config.js",21 });22 // Copy package.json file23 cy.task("copyFixture", {24 project,25 from: "package.json",26 to: "package.json",27 });28 // Copy Netlify settings29 cy.task("copyFixture", {30 project,31 from: "netlify.toml",32 to: "netlify.toml",33 });34 cy.task("copyFixture", {35 project,36 from: ".netlify",37 to: ".netlify",38 });39 // Build40 cy.task("buildProject", { project });41 // Deploy42 cy.task("deployProject", { project }, { timeout: 180 * 1000 });43 });44 // Set base URL45 cy.task("getBaseUrl", { project }).then((url) => {46 Cypress.config("baseUrl", url);47 });48});49after(() => {50 // While the before hook runs twice (it's re-run when the base URL changes),51 // the after hook only runs once.52 cy.task("clearDeployment");53});54describe("Page with optional catch all routing", () => {55 it("responds to base path", () => {56 cy.visit("/catch");57 cy.get("h1").should("contain", "Show #1");58 cy.get("p").should("contain", "Under the Dome");59 });60 it("responds to catch-all path", () => {61 cy.visit("/catch/25/catch/all");62 cy.get("h1").should("contain", "Show #25");63 cy.get("p").should("contain", "Hellsing");64 });65 it("loads page props from data .json file when navigating to it", () => {66 cy.visit("/");67 cy.window().then((w) => (w.noReload = true));68 // Navigate to page and test that no reload is performed69 // See: https://glebbahmutov.com/blog/detect-page-reload/70 cy.contains("/catch").click();71 cy.get("h1").should("contain", "Show #1");72 cy.get("p").should("contain", "Under the Dome");73 cy.contains("Go back home").click();74 cy.contains("/catch/25/catch/all").click();75 cy.get("h1").should("contain", "Show #25");76 cy.get("p").should("contain", "Hellsing");77 cy.contains("Go back home").click();78 cy.contains("/catch/75/undefined/path/test").click();79 cy.get("h1").should("contain", "Show #75");80 cy.get("p").should("contain", "The Mindy Project");81 cy.window().should("have.property", "noReload", true);82 });...
main.js
Source:main.js
1'use strict';2Object.defineProperty(exports, "__esModule", {3 value: true4});5var _fixtures;6function _load_fixtures() {7 return _fixtures = require('./fixtures');8}9Object.defineProperty(exports, 'generateHgRepo1Fixture', {10 enumerable: true,11 get: function () {12 return (_fixtures || _load_fixtures()).generateHgRepo1Fixture;13 }14});15Object.defineProperty(exports, 'generateHgRepo2Fixture', {16 enumerable: true,17 get: function () {18 return (_fixtures || _load_fixtures()).generateHgRepo2Fixture;19 }20});21Object.defineProperty(exports, 'copyFixture', {22 enumerable: true,23 get: function () {24 return (_fixtures || _load_fixtures()).copyFixture;25 }26});27Object.defineProperty(exports, 'copyBuildFixture', {28 enumerable: true,29 get: function () {30 return (_fixtures || _load_fixtures()).copyBuildFixture;31 }32});33var _matchers;34function _load_matchers() {35 return _matchers = require('./matchers');36}37Object.defineProperty(exports, 'addMatchers', {38 enumerable: true,39 get: function () {40 return (_matchers || _load_matchers()).addMatchers;41 }...
initFixture.js
Source:initFixture.js
...3import gitInit from "./gitInit";4export default initFixture;5async function initFixture(fixturePath, commitMessage = "Init commit") {6 const testDir = await tempy.directoryAsync();7 await copyFixture(testDir, fixturePath);8 await gitInit(testDir, commitMessage);9 return testDir;...
copyFixture.js
Source:copyFixture.js
1const { join } = require("path");2const { copySync } = require("fs-extra");3// Copy the fixture files from fixtures/ to the project folder4const copyFixture = ({ project, from, to }, config) => {5 copySync(6 join(config.fixturesFolder, from),7 join(config.buildsFolder, project, to)8 );9 return true;10};...
index.js
Source:index.js
1'use strict';2const { findFixture } = require('../find-fixture');3const fs = require('fs-extra');4module.exports.copyFixture = copyFixture;5function copyFixture(targetDir, fixtureName, cwd) {6 return findFixture(cwd, fixtureName).then((fp) => fs.copy(fp, targetDir));...
Using AI Code Generation
1var copyFixture = require('mocha').utils.copyFixture;2var path = require('path');3var src = path.join(__dirname, 'fixtures', 'foo.txt');4var dest = path.join(__dirname, 'fixtures', 'bar.txt');5copyFixture(src, dest, function(err){6 if (err) throw err;7});8var copyFixtures = require('mocha').utils.copyFixtures;9var path = require('path');10var src = path.join(__dirname, 'fixtures');11var dest = path.join(__dirname, 'fixtures', 'bar');12copyFixtures(src, dest, function(err){13 if (err) throw err;14});15- [TJ Holowaychuk](
Using AI Code Generation
1var copyFixture = require('mocha/lib/utils').copyFixture;2var path = require('path');3describe('Test', function () {4 it('should copy fixture', function () {5 var src = path.join(__dirname, 'fixtures', 'test.txt');6 var dest = path.join(__dirname, 'fixtures', 'test.txt');7 copyFixture(src, dest);8 });9});
Using AI Code Generation
1var MochaUtils = require('./MochaUtils');2var fs = require('fs');3describe('test', function() {4 it('test', function() {5 MochaUtils.copyFixture('test.txt', 'test.txt');6 var data = fs.readFileSync('test.txt', 'utf8');7 expect(data).to.equal('test');8 });9});
Using AI Code Generation
1var copyFixture = require('../lib/fixtures').copyFixture;2copyFixture('fixture1', 'fixture2');3copyFixture('fixture3', 'fixture4');4copyFixture('fixture5', 'fixture6');5copyFixture('fixture7', 'fixture8');6copyFixture('fixture9', 'fixture10');7var copyFixture = require('../lib/fixtures').copyFixture;8copyFixture('fixture1', 'fixture2', 'fixture3', 'fixture4', 'fixture5', 'fixture6', 'fixture7', 'fixture8', 'fixture9', 'fixture10');9var copyFixture = require('../lib/fixtures').copyFixture;10copyFixture('fixture1', 'fixture2', 'fixture3', 'fixture4', 'fixture5', 'fixture6', 'fixture7', 'fixture8', 'fixture9', 'fixture10');11var copyFixture = require('../lib/fixtures').copyFixture;12copyFixture('fixture1', 'fixture2', 'fixture3', 'fixture4', 'fixture5', 'fixture6', 'fixture7', 'fixture8', 'fixture9', 'fixture10');13var copyFixture = require('../lib/fixtures').copyFixture;14copyFixture('fixture1', 'fixture2', 'fixture3', 'fixture4', 'fixture5', 'fixture6', 'fixture7', 'fixture8', 'fixture9', 'fixture10');15var copyFixture = require('../lib/fixtures').copyFixture;16copyFixture('fixture1', 'fixture2', 'fixture3', 'fixture4', 'fixture5', 'fixture6', 'fixture7', 'fixture8', 'fixture9', 'fixture10');17var copyFixture = require('../lib/fixtures').copyFixture;18copyFixture('fixture1', 'fixture2', 'fixture3', 'fixture4', 'fixture5', 'fixture6', 'fixture7', 'fixture8', 'fixture9', 'fixture10');19var copyFixture = require('../lib/fixtures').copyFixture;20copyFixture('fixture1', 'fixture2', 'fixture3', 'fixture4', 'fixture5', 'fixture6', 'fixture7', 'fixture8', 'fixture9', 'fixture10');21var copyFixture = require('../lib/fixtures').copy
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!