UNPKG

nest-commander-testing

Version:

A testing utility for nest-commander. It builds on top of ideas from @nestjs/testing and is not tied to any test framework directly.

84 lines 3.51 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CommandTestFactory = void 0; const testing_1 = require("@nestjs/testing"); const crypto_1 = require("crypto"); const nest_commander_1 = require("nest-commander"); class CommandTestFactory { static useDefaultInquirer() { this.useOriginalInquirer = true; return this; } static createTestingCommand(moduleMetadata, options) { moduleMetadata.imports.push(nest_commander_1.CommandRunnerModule.forModule(undefined, options)); const testingModule = testing_1.Test.createTestingModule(moduleMetadata); if (!this.useOriginalInquirer) { testingModule.overrideProvider(nest_commander_1.Inquirer).useValue({ prompt: this.promptMock.bind(this), }); } return testingModule; } static async promptMock(questions, answers = {}) { var _a, _b, _c; for (let i = 0; i < questions.length; i++) { const question = questions[i]; if ((question.name && answers[question.name]) || !this.testAnswers[i]) { continue; } let answer; if (question.validate) { await question.validate(this.testAnswers[i]); } if (question.when && typeof question.when === 'function') { await question.when(answers); } if (question.choices) { let choices = question.choices; if (typeof choices === 'function') { choices = await choices(answers); } const choice = choices.find((c) => c.key === this.testAnswers[i]); answer = (choice === null || choice === void 0 ? void 0 : choice.value) || this.testAnswers[i]; } else { answer = this.testAnswers[i]; } if (question.default && typeof question.default === 'function') { await question.default(this.testAnswers); } if (question.message && typeof question.message === 'function') { await question.message(this.testAnswers); } answers[(_a = question.name) !== null && _a !== void 0 ? _a : 'default'] = (_c = (await ((_b = question.filter) === null || _b === void 0 ? void 0 : _b.call(question, answer, answers)))) !== null && _c !== void 0 ? _c : answer; } return answers; } static async run(app, args = []) { const application = await this.runApplication(app, args); await application.close(); } static async runWithoutClosing(app, args = []) { return this.runApplication(app, args); } static async runApplication(app, args = []) { if ((args === null || args === void 0 ? void 0 : args.length) && args[0] !== 'node') { args = ['node', (0, crypto_1.randomBytes)(8).toString('hex') + '.js'].concat(args); } await app.init(); const runner = app.get(nest_commander_1.CommandRunnerService); await runner.run(args); return app; } static setAnswers(value) { if (!Array.isArray(value)) { value = [value]; } this.testAnswers = value; } } exports.CommandTestFactory = CommandTestFactory; CommandTestFactory.testAnswers = []; CommandTestFactory.useOriginalInquirer = false; //# sourceMappingURL=command-test.factory.js.map