@orchestrator/ngx-testing
Version:
Testing utilities for Angular projects
634 lines (618 loc) • 23.3 kB
JavaScript
import { __assign, __spread, __decorate, __metadata, __awaiter, __generator, __extends } from 'tslib';
import { CommonModule } from '@angular/common';
import { InjectionToken, NgModule, ViewChild, Component, ComponentFactoryResolver, Injector, ɵɵdefineInjectable, ɵɵinject, INJECTOR, Injectable, Compiler, CompilerFactory } from '@angular/core';
import { TestBed, getTestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
var TestTypeKind;
(function (TestTypeKind) {
TestTypeKind[TestTypeKind["Component"] = 0] = "Component";
TestTypeKind[TestTypeKind["Directive"] = 1] = "Directive";
})(TestTypeKind || (TestTypeKind = {}));
var outputMockFactory = function () { return (function () { return null; }); };
var ɵ0 = outputMockFactory;
function setOutputMock(mock) {
outputMockFactory = mock;
}
function getOutputMock() {
return outputMockFactory;
}
/**
* @internal
*/
var TestModuleToken = new InjectionToken('TestModuleToken');
/**
* @internal
*/
var TestTypeToken = new InjectionToken('TestTypeToken');
/**
* @internal
*/
var TestTypeKindToken = new InjectionToken('TestTypeKindToken');
/**
* @internal
*/
var ExtraConfigToken = new InjectionToken('ExtraConfigToken');
/**
* @internal
*/
function getDirectiveIO(dirType) {
var propMeta = dirType['__prop__metadata__'];
var inputsMeta = filterPropMeta(propMeta, 'Input');
var outputsMeta = filterPropMeta(propMeta, 'Output');
return {
inputs: propMetaToTemplateBindings(inputsMeta),
outputs: propMetaToTemplateBindings(outputsMeta),
};
}
function propMetaToTemplateBindings(meta) {
return Object.keys(meta).map(function (propName) {
return ({
propName: propName,
templateName: meta[propName].bindingPropertyName || propName,
});
});
}
function filterPropMeta(obj, type) {
return Object.keys(obj).reduce(function (acc, k) {
var _a;
var meta = obj[k].find(function (m) { return m.ngMetadataName === type; });
return meta ? __assign(__assign({}, acc), (_a = {}, _a[k] = meta, _a)) : acc;
}, {});
}
/**
* @internal
*/
function get(type) {
return TestBed.get(type);
}
/**
* @internal
*/
function mergeArrays() {
var arrays = [];
for (var _i = 0; _i < arguments.length; _i++) {
arrays[_i] = arguments[_i];
}
return arrays.reduce(function (acc, arr) { return __spread(acc, toArray(arr)); }, []);
}
/**
* @internal
*/
function toArray(arr) {
return arr ? arr : [];
}
var NgxTestingModule = /** @class */ (function () {
function NgxTestingModule() {
}
NgxTestingModule.forComponent = function (compType, extras) {
if (extras === void 0) { extras = {}; }
var testModule = getTestingModuleFor(compType, compType, extras.ngModule);
return {
ngModule: testModule,
providers: [
{ provide: TestModuleToken, useValue: testModule },
{ provide: TestTypeToken, useValue: compType },
{ provide: TestTypeKindToken, useValue: TestTypeKind.Component },
{ provide: ExtraConfigToken, useValue: extras },
],
};
};
NgxTestingModule.forDirective = function (dirType, extras) {
if (extras === void 0) { extras = {}; }
var testModule = getTestingModuleFor(dirType, extras.hostComponent, extras.ngModule);
return {
ngModule: testModule,
providers: [
{ provide: TestModuleToken, useValue: testModule },
{ provide: TestTypeToken, useValue: dirType },
{ provide: TestTypeKindToken, useValue: TestTypeKind.Directive },
{ provide: ExtraConfigToken, useValue: extras },
],
};
};
NgxTestingModule = __decorate([
NgModule({
imports: [CommonModule],
exports: [CommonModule],
})
], NgxTestingModule);
return NgxTestingModule;
}());
function getTestingModuleFor(type, entryType, extra) {
if (extra === void 0) { extra = {}; }
var TestingModule = /** @class */ (function () {
function TestingModule() {
}
TestingModule = __decorate([
NgModule({
imports: mergeArrays(extra.imports, [NgxTestingModule]),
exports: mergeArrays(extra.exports, [NgxTestingModule, type]),
declarations: mergeArrays(extra.declarations, [type]),
entryComponents: entryType
? mergeArrays(extra.entryComponents, [entryType])
: extra.entryComponents,
schemas: extra.schemas,
})
], TestingModule);
return TestingModule;
}());
return TestingModule;
}
/**
* @internal
*/
function genHostCompTpl(tag, io, content, bindings) {
if (content === void 0) { content = ''; }
var inputsTpl = genInputsTpl(io.inputs);
var outputsTpl = genOutputsTpl(io.outputs);
var bindingsTpl = bindings
? typeof bindings === 'string'
? "let-" + bindings
: Object.keys(bindings)
.map(function (key) { return "let-" + key + (bindings[key] ? "=\"" + bindings[key] + "\"" : ''); })
.join(' ')
: '';
return "<" + tag + " " + inputsTpl + " " + outputsTpl + " " + bindingsTpl + ">" + content + "</" + tag + ">";
}
/**
* @internal
*/
function genHostCompTplStar(binding, tag, io, content, bindings) {
if (content === void 0) { content = ''; }
var inputsTpl = genInputsTplStar(binding, io.inputs, bindings);
return "<" + tag + " " + inputsTpl + ">" + content + "</" + tag + ">";
}
/**
* @internal
*/
function genInputsTplStar(binding, inputs, bindings) {
var inputsTpl = inputs
.filter(function (_a) {
var templateName = _a.templateName;
return templateName !== binding;
})
.map(function (_a) {
var templateName = _a.templateName, propName = _a.propName;
return templateName.replace(binding, '') + ": " + propName;
})
.join('; ');
var bindingsTpl = bindings
? typeof bindings === 'string'
? "let " + bindings
: Object.keys(bindings)
.map(function (key) { return "let " + key + (bindings[key] ? ": " + bindings[key] : ''); })
.join(', ')
: '';
return "*" + binding + "=\"" + binding + "; " + inputsTpl + "; " + bindingsTpl + "\"";
}
/**
* @internal
*/
function genInputsTpl(inputs) {
return inputs
.map(function (_a) {
var templateName = _a.templateName, propName = _a.propName;
return "[" + templateName + "]=\"" + propName + "\"";
})
.join(' ');
}
/**
* @internal
*/
function genOutputsTpl(outputs) {
return outputs
.map(function (_a) {
var templateName = _a.templateName, propName = _a.propName;
return "(" + templateName + ")=\"" + propName + "($event)\"";
})
.join(' ');
}
/**
* @internal
*/
var HostGeneratorService = /** @class */ (function () {
function HostGeneratorService(cfr, injector) {
this.cfr = cfr;
this.injector = injector;
this.testModule = this.injector.get(TestModuleToken);
this.typeToken = this.injector.get(TestTypeToken);
this.typeKind = this.injector.get(TestTypeKindToken);
this.extraConfig = this.injector.get(ExtraConfigToken);
}
HostGeneratorService.prototype.generateModuleFor = function (host) {
var testModule = this.testModule;
var ngModule = this.extraConfig.ngModule;
var TestModule = /** @class */ (function () {
function TestModule() {
}
TestModule = __decorate([
NgModule({
imports: [testModule],
declarations: [host],
exports: [host],
entryComponents: [host],
schemas: ngModule ? ngModule.schemas : [],
})
], TestModule);
return TestModule;
}());
return TestModule;
};
HostGeneratorService.prototype.generate = function () {
switch (this.typeKind) {
case TestTypeKind.Component:
return this.generateForComponent();
case TestTypeKind.Directive:
return this.generateForDirective();
default:
throw Error("HostGeneratorService: Cannot generate host component for unknown kind: " + this.typeKind);
}
};
HostGeneratorService.prototype.generateForComponent = function () {
return this.genForComponent(this.typeToken);
};
HostGeneratorService.prototype.generateForDirective = function () {
return this.genForDirective(this.typeToken);
};
HostGeneratorService.prototype.genForComponent = function (compType) {
var factory = this.cfr.resolveComponentFactory(compType);
var selector = "host-" + factory.selector;
var template = this.extraConfig.template ||
genHostCompTpl(factory.selector, factory, this.extraConfig.projectContent);
return this.genComponent({ selector: selector, template: template }, compType, factory);
};
HostGeneratorService.prototype.genForDirective = function (dirType) {
var io = getDirectiveIO(dirType);
var selector = 'host-directive';
var templateTag = this.extraConfig.template
? ''
: this.extraConfig.hostComponent
? this.cfr.resolveComponentFactory(this.extraConfig.hostComponent)
.selector
: this.extraConfig.hostTag;
var template = this.extraConfig.template ||
(templateTag ? this.genDirectiveTemplate(templateTag, io) : '');
return this.genComponent({ selector: selector, template: template }, dirType, io);
};
HostGeneratorService.prototype.genDirectiveTemplate = function (tag, io) {
return this.extraConfig.useStarSyntax
? genHostCompTplStar(io.inputs[0].templateName, tag, io, this.extraConfig.projectContent, this.extraConfig.templateBindings)
: genHostCompTpl(tag, io, this.extraConfig.projectContent, this.extraConfig.templateBindings);
};
HostGeneratorService.prototype.genComponent = function (meta, type, io) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
var hostGeneratorService = this;
var TestHostComponent = /** @class */ (function () {
function TestHostComponent() {
hostGeneratorService.initComponent(type, this, io);
}
__decorate([
ViewChild(type),
__metadata("design:type", Object)
], TestHostComponent.prototype, "instance", void 0);
TestHostComponent = __decorate([
Component(meta),
__metadata("design:paramtypes", [])
], TestHostComponent);
return TestHostComponent;
}());
return TestHostComponent;
};
HostGeneratorService.prototype.initComponent = function (compType, hostComp, io) {
io.inputs.forEach(function (_a) {
var propName = _a.propName;
return (hostComp[propName] = undefined);
});
io.outputs.forEach(function (_a) {
var propName = _a.propName;
return (hostComp[propName] = getOutputMock()(propName, compType.name, compType, function () { return hostComp.instance; }));
});
};
HostGeneratorService.ctorParameters = function () { return [
{ type: ComponentFactoryResolver },
{ type: Injector }
]; };
HostGeneratorService.ɵprov = ɵɵdefineInjectable({ factory: function HostGeneratorService_Factory() { return new HostGeneratorService(ɵɵinject(ComponentFactoryResolver), ɵɵinject(INJECTOR)); }, token: HostGeneratorService, providedIn: "root" });
HostGeneratorService = __decorate([
Injectable({
providedIn: 'root',
}),
__metadata("design:paramtypes", [ComponentFactoryResolver,
Injector])
], HostGeneratorService);
return HostGeneratorService;
}());
var Host = /** @class */ (function () {
function Host(injector) {
this.injector = injector;
this.hostGeneratorService = this.injector.get(HostGeneratorService);
this.componentType = this.injector.get(TestTypeToken);
this.hostComponentType = this.hostGeneratorService.generate();
this.compiler = this.injector.get(Compiler);
this._didCompilation = false;
}
Object.defineProperty(Host.prototype, "fixture", {
get: function () {
return this._fixture;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Host.prototype, "hostElement", {
get: function () {
return this._fixture.debugElement;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Host.prototype, "hostHtmlElement", {
get: function () {
return this._fixture.nativeElement;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Host.prototype, "hostComponent", {
get: function () {
return this._fixture.componentInstance;
},
enumerable: true,
configurable: true
});
Host.prototype.ngOnDestroy = function () {
if (this._fixture) {
try {
this._fixture.destroy();
}
catch (_a) { }
}
};
Host.prototype.compileComponents = function () {
return __awaiter(this, void 0, void 0, function () {
var hostModule;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!!this._didCompilation) return [3 /*break*/, 3];
this._didCompilation = true;
hostModule = this.hostGeneratorService.generateModuleFor(this.hostComponentType);
return [4 /*yield*/, this.compiler.compileModuleAndAllComponentsAsync(hostModule)];
case 1:
_a.sent();
return [4 /*yield*/, TestBed.compileComponents()];
case 2: return [2 /*return*/, _a.sent()];
case 3: return [2 /*return*/];
}
});
});
};
Host.prototype.createComponent = function (inputs, detectChanges) {
if (detectChanges === void 0) { detectChanges = false; }
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.compileComponents()];
case 1:
_a.sent();
this._fixture = TestBed.createComponent(this.hostComponentType);
if (inputs) {
this.setInputs(inputs);
}
if (detectChanges) {
this.detectChanges();
}
return [2 /*return*/, this._fixture];
}
});
});
};
Host.prototype.setInputs = function (inputs, detectChanges) {
if (detectChanges === void 0) { detectChanges = false; }
Object.assign(this.hostComponent, inputs);
if (detectChanges) {
this.detectChanges();
}
};
Host.prototype.overrideHostTemplate = function (tpl) {
TestBed.overrideTemplate(this.hostComponentType, tpl);
};
Host.prototype.detectChanges = function (checkNoChanges) {
this._fixture.detectChanges(checkNoChanges);
};
Host.prototype.query = function (compOrDir) {
return this.hostElement.query(By.directive(compOrDir));
};
Host.prototype.queryComponent = function (compOrDir) {
var elem = this.query(compOrDir);
return elem ? elem.componentInstance : undefined;
};
Host.prototype.queryComponentHtml = function (compOrDir) {
var elem = this.query(compOrDir);
return elem ? elem.nativeElement : undefined;
};
Host.prototype.queryCss = function (css) {
return this.hostElement.query(By.css(css));
};
return Host;
}());
var HostComponentService = /** @class */ (function (_super) {
__extends(HostComponentService, _super);
function HostComponentService(injector) {
return _super.call(this, injector) || this;
}
Object.defineProperty(HostComponentService.prototype, "element", {
get: function () {
return this.query(this.componentType);
},
enumerable: true,
configurable: true
});
Object.defineProperty(HostComponentService.prototype, "htmlElement", {
get: function () {
return this.queryComponentHtml(this.componentType);
},
enumerable: true,
configurable: true
});
Object.defineProperty(HostComponentService.prototype, "component", {
get: function () {
return this.element.componentInstance;
},
enumerable: true,
configurable: true
});
HostComponentService.ctorParameters = function () { return [
{ type: Injector }
]; };
HostComponentService.ɵprov = ɵɵdefineInjectable({ factory: function HostComponentService_Factory() { return new HostComponentService(ɵɵinject(INJECTOR)); }, token: HostComponentService, providedIn: "root" });
HostComponentService = __decorate([
Injectable({
providedIn: 'root',
}),
__metadata("design:paramtypes", [Injector])
], HostComponentService);
return HostComponentService;
}(Host));
var HostDirectiveService = /** @class */ (function (_super) {
__extends(HostDirectiveService, _super);
function HostDirectiveService(injector) {
return _super.call(this, injector) || this;
}
Object.defineProperty(HostDirectiveService.prototype, "directive", {
get: function () {
return this.hostComponent.instance;
},
enumerable: true,
configurable: true
});
HostDirectiveService.ctorParameters = function () { return [
{ type: Injector }
]; };
HostDirectiveService.ɵprov = ɵɵdefineInjectable({ factory: function HostDirectiveService_Factory() { return new HostDirectiveService(ɵɵinject(INJECTOR)); }, token: HostDirectiveService, providedIn: "root" });
HostDirectiveService = __decorate([
Injectable({
providedIn: 'root',
}),
__metadata("design:paramtypes", [Injector])
], HostDirectiveService);
return HostDirectiveService;
}(Host));
function getTestingForComponent(type, extras) {
var testModule = NgxTestingModule.forComponent(type, extras);
var getHost = function () {
return TestBed.inject(HostComponentService);
};
var createComponent = function (inputs, detectChanges) {
return getHost()
.createComponent(inputs, detectChanges)
.then(getHost);
};
return { testModule: testModule, getHost: getHost, createComponent: createComponent };
}
function getTestingForDirective(type, extras) {
var testModule = NgxTestingModule.forDirective(type, extras);
var getHost = function () {
return TestBed.inject(HostDirectiveService);
};
var createComponent = function (inputs, detectChanges) {
return getHost()
.createComponent(inputs, detectChanges)
.then(getHost);
};
return { testModule: testModule, getHost: getHost, createComponent: createComponent };
}
var compilerFactory;
var compiler;
afterEach(resetModuleCompiler);
/**
* Allows to compile and instantiate any {@link NgModule}
* with optional custom {@link Injector} or {@link StaticProvider}s
*
* _NOTE:_ Compiler is reused between test cases unless `options` are passed -
* in which case a new compiler will be created and reused for the current test case
*
* **Example:**
* ```ts
* import { NgModule } from '@angular/core';
*
* @NgModule({...})
* class MyModule {}
*
* it('should instantiate MyModule', () => {
* const myModule = createModule(MuModule);
* expect(myModule instanceof MyModule).toBeTruthy();
* });
* ```
*
* For async module compilation use {@link createModuleAsync()}
*/
function createModule(moduleType, injectorOrProviders, options) {
if (injectorOrProviders === void 0) { injectorOrProviders = Injector.NULL; }
var moduleDef = createCompiler(options).compileModuleAndAllComponentsSync(moduleType);
return instantiateModule(moduleDef.ngModuleFactory, injectorOrProviders);
}
/**
* Allows to compile and instantiate any {@link NgModule}
* with optional custom {@link Injector} or {@link StaticProvider}s
* in asynchronous manner
*
* Works same as {@link createModule()} but compiles module asynchronously
* @see createModule()
*/
function createModuleAsync(moduleType, injectorOrProviders, options) {
if (injectorOrProviders === void 0) { injectorOrProviders = Injector.NULL; }
return __awaiter(this, void 0, void 0, function () {
var moduleDef;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, createCompiler(options).compileModuleAndAllComponentsAsync(moduleType)];
case 1:
moduleDef = _a.sent();
return [2 /*return*/, instantiateModule(moduleDef.ngModuleFactory, injectorOrProviders)];
}
});
});
}
/**
* Allows to reset {@link Compiler} used to compile modules for current test case
* created via {@link createModule()} and {@link createModuleAsync()}
*/
function resetModuleCompiler() {
compiler = undefined;
}
function instantiateModule(moduleFactory, injectorOrProviders) {
if (injectorOrProviders === void 0) { injectorOrProviders = Injector.NULL; }
if (Array.isArray(injectorOrProviders)) {
injectorOrProviders = Injector.create({ providers: injectorOrProviders });
}
return moduleFactory.create(injectorOrProviders);
}
function createCompiler(options) {
if (!compiler || options) {
compiler = getCompilerFactory().createCompiler(options);
}
return compiler;
}
function getCompilerFactory() {
if (!compilerFactory) {
compilerFactory = getTestBed().platform.injector.get(CompilerFactory);
}
return compilerFactory;
}
/**
* @internal
*
* Used to simulate complete reset inside unit tests
*/
function _reset() {
compilerFactory = undefined;
compiler = undefined;
}
/*
* Public API Surface of ngx-testing
*/
/**
* Generated bundle index. Do not edit.
*/
export { Host, HostComponentService, HostDirectiveService, NgxTestingModule, TestTypeKind, createModule, createModuleAsync, getOutputMock, getTestingForComponent, getTestingForDirective, resetModuleCompiler, setOutputMock, ɵ0 };
//# sourceMappingURL=orchestrator-ngx-testing.js.map