Skip to content

Commit

Permalink
Merge b76c817 into 4aa2cb9
Browse files Browse the repository at this point in the history
  • Loading branch information
mshima committed Jan 31, 2020
2 parents 4aa2cb9 + b76c817 commit 8972830
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 3 deletions.
22 changes: 19 additions & 3 deletions lib/run-context.js
Expand Up @@ -12,6 +12,21 @@ var EventEmitter = require('events').EventEmitter;
var helpers = require('./');
var TestAdapter = require('./adapter').TestAdapter;

/**
* Wrap callback so it can't get called twice
*/
const callbackWrapper = done => {
let callbackHandled = false;
const callback = err => {
if (!callbackHandled) {
callbackHandled = true;
done(err);
}
};

return callback;
};

/**
* This class provide a run context object to façade the complexity involved in setting
* up a generator for testing
Expand Down Expand Up @@ -108,14 +123,15 @@ RunContext.prototype._run = function() {
helpers.mockLocalConfig(this.generator, this.localConfig);
}

this.generator.on(
'error',
const callback = callbackWrapper(
function(err) {
if (!this.emit('error', err)) {
throw err;
}
}.bind(this)
);

this.generator.on('error', callback);
this.generator.once(
'end',
function() {
Expand All @@ -129,7 +145,7 @@ RunContext.prototype._run = function() {

const generatorPromise = this.generator.run();
if (!this.settings.compatibility) {
generatorPromise.catch(err => this.emit('error', err));
generatorPromise.catch(callback);
}
};

Expand Down
52 changes: 52 additions & 0 deletions test/helpers.js
Expand Up @@ -181,5 +181,57 @@ describe('yeoman-test', function() {
var runContext = helpers.run(helpers.createDummyGenerator(), { foo: 1 });
assert.equal(runContext.settings.foo, 1);
});

it('catch env errors', function(done) {
helpers
.run(
class extends helpers.createDummyGenerator() {
throws() {
this.env.emit('error', new Error());
}
}
)
.on('error', _ => {
done();
});
});

it('catch generator emitted errors', function(done) {
helpers
.run(
class extends helpers.createDummyGenerator() {
throws() {
this.emit('error', new Error());
}
}
)
.on('error', _ => {
done();
});
});

it('catch generator thrown errors', function(done) {
helpers
.run(
class extends helpers.createDummyGenerator() {
throws() {
throw new Error();
}
}
)
.on('error', _ => {
done();
});
});

// This is a workaround for corner case were an error is not correctly emitted
// See https://github.com/yeoman/generator/pull/1155
it('catch run errors', function(done) {
helpers
.run(class extends Generator {}, { catchGeneratorError: true })
.on('error', _ => {
done();
});
});
});
});

0 comments on commit 8972830

Please sign in to comment.