From d0e5efc435f40445718d6ce64604996073b37783 Mon Sep 17 00:00:00 2001 From: MG Date: Sat, 28 Nov 2020 12:08:55 +0100 Subject: [PATCH 1/2] fix: a contemporary example --- .editorconfig | 12 + .prettierrc.yml | 3 + README.md | 105 ++--- examples/MAIN/test.spec.ts | 34 +- examples/MockBuilder/test.deep.spec.ts | 245 ++++++++++ examples/MockBuilder/test.promise.spec.ts | 37 ++ examples/MockBuilder/test.simple.spec.ts | 23 + examples/MockBuilder/test.spec.ts | 223 ---------- examples/MockComponent/test.spec.ts | 34 +- examples/MockDirective-Attribute/test.spec.ts | 30 +- .../MockDirective-Structural/test.spec.ts | 30 +- examples/MockForms/test.spec.ts | 22 +- examples/MockInstance/test.spec.ts | 18 +- examples/MockModule/test.spec.ts | 21 +- examples/MockObservable/test.spec.ts | 18 +- examples/MockPipe/test.spec.ts | 18 +- examples/MockProvider/test.spec.ts | 29 +- examples/MockReactiveForms/test.spec.ts | 16 +- examples/MockRender/test.spec.ts | 40 +- examples/NG_MOCKS/NG_MOCKS.spec.ts | 215 ++++++--- examples/TestAttributeDirective/test.spec.ts | 28 +- examples/TestHttpInterceptor/test.spec.ts | 31 +- examples/TestHttpRequest/test.spec.ts | 16 +- examples/TestLifecycleHooks/test.spec.ts | 13 +- examples/TestMultiToken/test.spec.ts | 4 +- examples/TestPipe/test.spec.ts | 1 + examples/TestProvider/test.spec.ts | 1 + examples/TestProviderInComponent/test.spec.ts | 1 + examples/TestProviderInDirective/test.spec.ts | 10 +- .../TestProviderWithDependencies/test.spec.ts | 1 + .../TestProviderWithUseClass/test.spec.ts | 1 + .../TestProviderWithUseExisting/test.spec.ts | 1 + .../TestProviderWithUseFactory/test.spec.ts | 1 + .../TestProviderWithUseValue/test.spec.ts | 1 + examples/TestRoute/test.spec.ts | 28 +- examples/TestRoutingGuard/test.spec.ts | 38 +- examples/TestRoutingResolver/test.spec.ts | 20 +- examples/TestStructuralDirective/test.spec.ts | 13 +- .../test.spec.ts | 11 +- examples/TestToken/test.spec.ts | 11 +- examples/ngMocksFaster/test.spec.ts | 43 +- examples/ngMocksGuts/test.spec.ts | 43 +- lib/common/jit-reflector.spec.ts | 16 +- lib/common/mock.spec.ts | 44 +- .../mock-builder.performance.spec.ts | 417 ++++++++++++++---- lib/mock-builder/mock-builder.promise.spec.ts | 22 +- lib/mock-builder/promise/types.ts | 4 +- lib/mock-component/mock-component.spec.ts | 171 +++++-- lib/mock-declaration/mock-declaration.spec.ts | 18 +- lib/mock-directive/mock-directive.spec.ts | 114 +++-- lib/mock-helper/mock-helper.guts.spec.ts | 287 +++++++++--- lib/mock-helper/mock-helper.spec.ts | 167 +++++-- lib/mock-module/mock-module.spec.ts | 61 ++- lib/mock-pipe/mock-pipe.spec.ts | 41 +- lib/mock-provider/mock-provider.spec.ts | 4 +- lib/mock-render/mock-render.spec.ts | 64 ++- lib/mock-service/mock-service.spec.ts | 223 +++++++--- package.release.json | 32 +- tests/NG_MOCKS_ROOT_PROVIDERS/test.spec.ts | 47 +- .../context-with-directives.spec.ts | 69 ++- .../test.spec.ts | 107 +++-- .../test.spec.ts | 39 +- tests/correct-module-exports-11/test.spec.ts | 29 +- tests/double-decorator/example-1.spec.ts | 18 +- tests/double-decorator/example-2.spec.ts | 18 +- tests/double-decorator/example-3.spec.ts | 48 +- tests/double-decorator/with-selector.spec.ts | 60 ++- .../without-selector-ivy.spec.ts | 43 +- .../double-decorator/without-selector.spec.ts | 41 +- tests/export-all/test.spec.ts | 17 +- tests/exports-only/test.spec.ts | 24 +- tests/get-inputs-and-outputs/test.spec.ts | 44 +- tests/get-mocked-ng-def-of/test.spec.ts | 26 +- .../injected-ng-templates.spec.ts | 38 +- tests/interceptor-kept-mocked/test.spec.ts | 23 +- tests/internal-only-nested/test.spec.ts | 16 +- tests/internal-only/test.spec.ts | 16 +- tests/internal-vs-external/test.spec.ts | 35 +- tests/is-mock-of/test.spec.ts | 32 +- tests/is-mocked-ng-def-of/test.spec.ts | 16 +- tests/issue-142/test.spec.ts | 11 +- tests/issue-151/test.spec.ts | 9 +- tests/issue-157/test.spec.ts | 18 +- tests/issue-162/test.spec.ts | 33 +- tests/issue-166/test.spec.ts | 3 +- tests/issue-167/NG_VALIDATORS.spec.ts | 26 +- tests/issue-167/component.spec.ts | 15 +- tests/issue-167/directive.spec.ts | 24 +- tests/issue-170/test.spec.ts | 17 +- tests/issue-172/test.spec.ts | 23 +- tests/issue-175/fixtures.ts | 80 ++++ tests/issue-175/test.spec.ts | 221 +++++----- tests/issue-177/test.spec.ts | 3 +- tests/issue-178/test.spec.ts | 6 +- tests/issue-181/test.spec.ts | 20 +- tests/issue-197/with-providers.spec.ts | 35 +- tests/issue-218/test.spec.ts | 30 +- tests/issue-222/app-initializer.spec.ts | 24 +- tests/issue-222/common-module.spec.ts | 10 +- .../issue-222/dom-shared-styles-host.spec.ts | 32 +- tests/issue-222/injector-scope.spec.ts | 16 +- tests/issue-222/kept-root-injection.spec.ts | 17 +- tests/issue-222/mock-keep-priorities.spec.ts | 45 +- tests/mock-builder-by-directive/test.spec.ts | 22 +- .../test.spec.ts | 10 +- tests/mock-render-all-properties/test.spec.ts | 11 +- .../test.spec.ts | 82 +++- tests/module-with-factory-tokens/test.spec.ts | 40 +- tests/module-with-tokens/test.spec.ts | 42 +- tests/multi-tokens/test.spec.ts | 11 +- .../fixtures.ts | 26 ++ .../test.fixture.spec.ts | 333 ++++++++++++++ .../test.no-fixture.spec.ts | 43 ++ .../test.spec.ts | 248 ----------- .../test.spec.ts | 24 +- tests/on-push/on-push.spec.ts | 6 +- tests/performance/test.spec.ts | 12 +- tests/pipe-as-service/test.spec.ts | 131 ++++-- .../test.spec.ts | 63 ++- tests/provider-with-dependency/test.spec.ts | 12 +- .../test.spec.ts | 20 +- tests/root-provider-in-depths/test.spec.ts | 12 +- .../root-provider-with-root-dep/test.spec.ts | 13 +- .../test.spec.ts | 8 +- tests/root-providers/fixtures.ts | 93 ++++ tests/root-providers/test.spec.ts | 225 +++++----- tests/shared-mocked-module/test.spec.ts | 28 +- tests/spies/test.spec.ts | 56 ++- .../structural-directives.spec.ts | 161 +++++-- tests/tokens-class/test.spec.ts | 4 +- tests/tokens-existing/test.spec.ts | 4 +- tslint.json | 1 + 132 files changed, 4660 insertions(+), 1780 deletions(-) create mode 100644 .editorconfig create mode 100644 examples/MockBuilder/test.deep.spec.ts create mode 100644 examples/MockBuilder/test.promise.spec.ts create mode 100644 examples/MockBuilder/test.simple.spec.ts delete mode 100644 examples/MockBuilder/test.spec.ts create mode 100644 tests/issue-175/fixtures.ts create mode 100644 tests/ng-mocks-search-with-no-fixture/fixtures.ts create mode 100644 tests/ng-mocks-search-with-no-fixture/test.fixture.spec.ts create mode 100644 tests/ng-mocks-search-with-no-fixture/test.no-fixture.spec.ts delete mode 100644 tests/ng-mocks-search-with-no-fixture/test.spec.ts create mode 100644 tests/root-providers/fixtures.ts diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000000..74844224cb --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +# Editor configuration, see http://editorconfig.org +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 2 +indent_style = space +insert_final_newline = true +max_line_length = 120 +tab_width = 2 +trim_trailing_whitespace = true diff --git a/.prettierrc.yml b/.prettierrc.yml index f0f76624e2..ebb8fbf676 100644 --- a/.prettierrc.yml +++ b/.prettierrc.yml @@ -14,3 +14,6 @@ overrides: - files: 'README.md' options: printWidth: 70 + - files: '*.spec.ts' + options: + printWidth: 70 diff --git a/README.md b/README.md index 7b7320ffec..8098e1a368 100644 --- a/README.md +++ b/README.md @@ -4,10 +4,13 @@ [![coverage status](https://img.shields.io/coveralls/github/ike18t/ng-mocks/master)](https://coveralls.io/github/ike18t/ng-mocks?branch=master) [![language grade](https://img.shields.io/lgtm/grade/javascript/g/ike18t/ng-mocks)](https://lgtm.com/projects/g/ike18t/ng-mocks/context:javascript) -# ng-mocks - ease of creating mock declarations out of annoying dependencies in Angular unit tests +# Create mock components and more out of annoying dependencies in Angular tests -`ng-mocks` is a library for testing Angular 5+ applications which provides helper functions for **creating mock components**, directives, pipes, modules and services. -Whether you need a **mock child component**, or any other annoying dependency, `ng-mocks` has a tool to turn this declaration into its mock copy, +`ng-mocks` is a library which provides helper functions for +**creating mock components**, directives, pipes, modules and services +for easy testing of Angular 5+ applications. +Whether you need a **mock child component**, or any other annoying dependency, +`ng-mocks` has a tool to turn this declaration into its mock copy, keeping its interface as it is, but suppressing its implementation. The current version of the library has been tested and can be used with: @@ -383,7 +386,6 @@ describe('MockComponent', () => { // ).componentInstance // but properly typed. const mockComponent = ngMocks.find( - fixture, 'app-child', ).componentInstance; @@ -407,7 +409,7 @@ describe('MockComponent', () => { // By.directive(DependencyComponent) // ).componentInstance // but properly typed. - const mockComponent = ngMocks.find(fixture, DependencyComponent) + const mockComponent = ngMocks.find(DependencyComponent) .componentInstance; // Again, let's pretend DependencyComponent has an output @@ -463,10 +465,8 @@ describe('MockComponent', () => { // The rendered template is wrapped by
. // We can use this selector to assert exactly its content. - const mockNgTemplate = ngMocks.find( - fixture.debugElement, - '[data-key="something"]', - ).nativeElement.innerHTML; + const mockNgTemplate = ngMocks.find('[data-key="something"]') + .nativeElement.innerHTML; expect(mockNgTemplate).toContain('

inside template

'); }); }); @@ -574,7 +574,7 @@ describe('MockDirective:Attribute', () => { // ).injector.get(DependencyDirective) // but easier and more precise. const mockDirective = ngMocks.get( - ngMocks.find(fixture.debugElement, 'span'), + ngMocks.find('span'), DependencyDirective, ); @@ -599,7 +599,7 @@ describe('MockDirective:Attribute', () => { // ).injector.get(DependencyDirective) // but easier and more precise. const mockDirective = ngMocks.get( - ngMocks.find(fixture.debugElement, 'span'), + ngMocks.find('span'), DependencyDirective, ); @@ -648,24 +648,19 @@ describe('MockDirective:Structural', () => { // Let's assert that nothing has been rendered inside of // the structural directive by default. - expect( - fixture.debugElement.nativeElement.innerHTML, - ).not.toContain('>content<'); + expect(fixture.nativeElement.innerHTML).not.toContain( + '>content<', + ); // And let's render it manually now. - const mockDirective = ngMocks.findInstance( - fixture.debugElement, - DependencyDirective, - ); + const mockDirective = ngMocks.findInstance(DependencyDirective); if (isMockOf(mockDirective, DependencyDirective, 'd')) { mockDirective.__render(); fixture.detectChanges(); } // The content of the structural directive should be rendered. - expect(fixture.debugElement.nativeElement.innerHTML).toContain( - '>content<', - ); + expect(fixture.nativeElement.innerHTML).toContain('>content<'); }); }); ``` @@ -763,8 +758,9 @@ describe('MockPipe', () => { it('transforms values to json', () => { const fixture = MockRender(TestedComponent); - const pipeElement = ngMocks.find(fixture.debugElement, 'span'); - expect(pipeElement.nativeElement.innerHTML).toEqual('["foo"]'); + expect(fixture.nativeElement.innerHTML).toEqual( + '["foo"]', + ); }); }); ``` @@ -1112,17 +1108,16 @@ If we created a fixture, we would face an error about reading properties of `und returns a spy, if [auto spy](#auto-spy) has been configured, or `undefined`. Therefore, neither has the `subscribe` property. Obviously, to solve this, we need to get the method to return an observable stream. -For that, we could create a mock copy via [`MockService`](#how-to-create-a-mock-service) and to pass it as the second parameter into [`MockProvider`](#how-to-create-a-mock-provider). +For that, we could extend a mock copy via passing overrides as the second parameter into [`MockProvider`](#how-to-create-a-mock-provider). ```typescript -const todoServiceMock = MockService(TodoService); -ngMocks.stub(todoServiceMock, { - list$: () => EMPTY, -}); - TestBed.configureTestingModule({ declarations: [TodoComponent], - providers: [MockProvider(TodoService, todoServiceMock)], + providers: [ + MockProvider(TodoService, { + list$: () => EMPTY, + }), + ], }); ``` @@ -1138,14 +1133,14 @@ let todoServiceList$: Subject; // <- a context variable. beforeEach(() => { todoServiceList$ = new Subject(); // <- create the subject. - const todoServiceMock = MockService(TodoService); - ngMocks.stub(todoServiceMock, { - list$: () => todoServiceList$, - }); TestBed.configureTestingModule({ declarations: [TodoComponent], - providers: [MockProvider(TodoService, todoServiceMock)], + providers: [ + MockProvider(TodoService, { + list$: () => todoServiceList$, + }), + ], }); }); @@ -1164,15 +1159,10 @@ let todoServiceList$: Subject; // <- a context variable. beforeEach(() => { todoServiceList$ = new Subject(); // <- create the subject. - const todoServiceMock = MockService(TodoService); - ngMocks.stub(todoServiceMock, { + + return MockBuilder(TodoComponent).mock(TodoService, { list$: () => todoServiceList$, }); - - return MockBuilder(TodoComponent).mock( - TodoService, - todoServiceMock, - ); }); it('test', () => { @@ -1246,6 +1236,11 @@ describe('MockObservable', () => { expect(fixture.nativeElement.innerHTML).not.toContain('1'); expect(fixture.nativeElement.innerHTML).not.toContain('2'); expect(fixture.nativeElement.innerHTML).not.toContain('3'); + + // Checking that a sibling method has been replaced + // with a mock copy too. + expect(TestBed.inject(TargetService).getValue$).toBeDefined(); + expect(TestBed.inject(TargetService).getValue$()).toBeUndefined(); }); }); ``` @@ -1289,10 +1284,8 @@ describe('MockReactiveForms', () => { const component = fixture.point.componentInstance; // Let's find the mock form component. - const mockControl = ngMocks.find( - fixture.debugElement, - DependencyComponent, - ).componentInstance; + const mockControl = ngMocks.find(DependencyComponent) + .componentInstance; // Let's simulate its change, like a user does it. if (isMockOf(mockControl, DependencyComponent, 'c')) { @@ -1334,10 +1327,8 @@ describe('MockForms', () => { const component = fixture.point.componentInstance; // Let's find the mock form component. - const mockControl = ngMocks.find( - fixture.debugElement, - DependencyComponent, - ).componentInstance; + const mockControl = ngMocks.find(DependencyComponent) + .componentInstance; // Let's simulate its change, like a user does it. if (isMockOf(mockControl, DependencyComponent, 'c')) { @@ -1426,9 +1417,7 @@ class AppComponent { }) class AppHeaderComponent { @Output() public readonly logo = new EventEmitter(); - @ContentChild('menu') public menu?: TemplateRef; - @Input() public showLogo = false; @Input() public title = ''; } @@ -1612,12 +1601,11 @@ and has a rich toolkit that supports: The source file is here: [MockBuilder](https://github.com/ike18t/ng-mocks/blob/master/examples/MockBuilder/test.spec.ts).
Prefix it with `fdescribe` or `fit` on -[codesandbox.io](https://codesandbox.io/s/github/ng-mocks/examples?file=/src/examples/MockBuilder/test.spec.ts) +[codesandbox.io](https://codesandbox.io/s/github/ng-mocks/examples?file=/src/examples/MockBuilder/test.simple.spec.ts) to play with. ```typescript describe('MockBuilder:simple', () => { - // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(MyComponent, MyModule)); // The same as // beforeEach(() => TestBed.configureTestingModule({{ @@ -1629,7 +1617,7 @@ describe('MockBuilder:simple', () => { it('should render content ignoring all dependencies', () => { const fixture = MockRender(MyComponent); expect(fixture).toBeDefined(); - expect(fixture.debugElement.nativeElement.innerHTML).toContain( + expect(fixture.nativeElement.innerHTML).toContain( '
My Content
', ); }); @@ -2110,6 +2098,9 @@ describe('MockRender', () => { it('renders inputs and outputs automatically', () => { const spy = jasmine.createSpy(); + // in case of jest + // const logoClickSpy = jest.fn(); + // Generates a template like: // . @@ -2271,9 +2262,7 @@ describe('MockInstance', () => { it('should render', () => { // Without the custom initialization rendering would fail here // with "Cannot read property 'subscribe' of undefined". - expect(() => MockRender(RealComponent)).not.toThrowError( - /Cannot read property 'subscribe' of undefined/, - ); + expect(() => MockRender(RealComponent)).not.toThrow(); }); }); ``` diff --git a/examples/MAIN/test.spec.ts b/examples/MAIN/test.spec.ts index 2903644c9d..df176ed474 100644 --- a/examples/MAIN/test.spec.ts +++ b/examples/MAIN/test.spec.ts @@ -1,7 +1,16 @@ -// tslint:disable arrow-return-shorthand +// tslint:disable arrow-return-shorthand strict-type-predicates import { CommonModule } from '@angular/common'; -import { Component, ContentChild, ElementRef, EventEmitter, Input, NgModule, Output, TemplateRef } from '@angular/core'; +import { + Component, + ContentChild, + ElementRef, + EventEmitter, + Input, + NgModule, + Output, + TemplateRef, +} from '@angular/core'; import { RouterModule } from '@angular/router'; import { MockBuilder, MockRender, ngMocks } from 'ng-mocks'; @@ -11,7 +20,11 @@ import { staticFalse } from '../../tests'; @Component({ selector: 'app-root', template: ` - +
  • Home
  • @@ -32,15 +45,17 @@ class AppComponent { @Component({ selector: 'app-header', template: ` - + + + {{ title }} `, }) class AppHeaderComponent { @Output() public readonly logo = new EventEmitter(); - - @ContentChild('menu', staticFalse) public menu?: TemplateRef; + @ContentChild('menu', staticFalse) + public menu?: TemplateRef; @Input() public showLogo = false; @Input() public title = ''; } @@ -107,7 +122,8 @@ describe('MAIN', () => { }); it('asserts behavior of AppComponent', () => { - const logoClickSpy = jasmine.createSpy(); + const logoClickSpy = + typeof jest === 'undefined' ? jasmine.createSpy() : jest.fn(); // in case of jest // const logoClickSpy = jest.fn(); @@ -139,7 +155,9 @@ describe('MAIN', () => { // Checking that AppComponents updates AppHeaderComponent. fixture.componentInstance.title = 'Updated Application'; fixture.detectChanges(); - expect(header.componentInstance.title).toBe('Updated Application'); + expect(header.componentInstance.title).toBe( + 'Updated Application', + ); // Checking that AppComponent listens on outputs of // AppHeaderComponent. diff --git a/examples/MockBuilder/test.deep.spec.ts b/examples/MockBuilder/test.deep.spec.ts new file mode 100644 index 0000000000..ef6d9a8b13 --- /dev/null +++ b/examples/MockBuilder/test.deep.spec.ts @@ -0,0 +1,245 @@ +import { HttpBackend, HttpClientModule } from '@angular/common/http'; +import { HttpClientTestingModule } from '@angular/common/http/testing'; +import { inject, TestBed } from '@angular/core/testing'; +import { MockBuilder, MockRender } from 'ng-mocks'; + +import { + ComponentContentChild, + ComponentWeDontWantToMimic, + ComponentWeWantToMimic, + MyComponent, + MyComponent1, + MyComponent2, + MyComponent3, +} from './fixtures.components'; +import { + DirectiveWeDontWantToMimic, + DirectiveWeWantToMimic, + MyDirective, +} from './fixtures.directives'; +import { + ModuleWeDontWantToMimic, + ModuleWeWantToMimicBesidesMyModule, + MyModule, +} from './fixtures.modules'; +import { + MyPipe, + PipeWeDontWantToMimicPipe, + PipeWeWantToCustomize, + PipeWeWantToMimicPipe, + PipeWeWantToRestore, +} from './fixtures.pipes'; +import { + AnythingWeWant1, + AnythingWeWant2, + MyCustomProvider1, + MyCustomProvider2, + MyCustomProvider3, + MyService1, + MyService2, + ServiceWeDontWantToMimic, + ServiceWeWantToCustomize, + ServiceWeWantToMimic, + TheSameAsAnyProvider, +} from './fixtures.services'; +import { + INJECTION_TOKEN_WE_DONT_WANT_TO_MIMIC, + INJECTION_TOKEN_WE_WANT_TO_CUSTOMIZE, + INJECTION_TOKEN_WE_WANT_TO_MIMIC, +} from './fixtures.tokens'; + +describe('MockBuilder:deep', () => { + beforeEach(async () => { + const ngModule = MockBuilder(MyComponent, MyModule) + .mock(ComponentContentChild, { + render: { + block: { + $implicit: '-$implicit-', + variables: { a: { z: 'b' } }, + }, + }, + }) + + .keep(ModuleWeDontWantToMimic, { + dependency: true, + }) + .keep(ComponentWeDontWantToMimic, { + dependency: true, + }) + .keep(DirectiveWeDontWantToMimic, { + dependency: true, + }) + .keep(PipeWeDontWantToMimicPipe, { + dependency: true, + }) + .keep(ServiceWeDontWantToMimic) + .keep(INJECTION_TOKEN_WE_DONT_WANT_TO_MIMIC) + + // The same can be done with Components, Directives and Pipes. + // For Providers use .provider() or .mock(). + .replace(HttpClientModule, HttpClientTestingModule, { + dependency: true, + }) + + .mock(ModuleWeWantToMimicBesidesMyModule, { + dependency: true, + }) + .mock(ComponentWeWantToMimic, { + dependency: true, + }) + .mock(DirectiveWeWantToMimic, { + dependency: true, + render: { + $implicit: { a: '$' }, + variables: { a: { b: 'b' } }, + }, + }) + .mock(PipeWeWantToMimicPipe, { + dependency: true, + }) + .mock(ServiceWeWantToMimic) // makes all methods an empty function + .mock(INJECTION_TOKEN_WE_WANT_TO_MIMIC) // makes its value undefined + + .mock(PipeWeWantToCustomize, () => 'My Custom Result') + .mock(PipeWeWantToRestore, () => 'My Restored Pipe') + .mock(ServiceWeWantToCustomize, { + getName: () => 'My Customized String', + }) + .mock(INJECTION_TOKEN_WE_WANT_TO_CUSTOMIZE, 'My_Token') + + // All providers will be set into the TestModule. + .provide({ + provide: AnythingWeWant1, + useValue: new TheSameAsAnyProvider(), + }) + .provide({ + provide: AnythingWeWant2, + useFactory: () => new TheSameAsAnyProvider(), + }) + .provide(MyCustomProvider1) + .provide([MyCustomProvider2, MyCustomProvider3]) + + // Now the pipe won't be replaced with its mock copy. + .keep(PipeWeWantToRestore) + + // Extra configuration. + .keep(MyDirective) + .keep(MyPipe) + .mock(MyService1) + .keep(MyService2) + + // Even it belongs to the module that is marked as kept, + // the component will be replaced with its mock copy. + .mock(MyComponent3) + + // and now we want to build our NgModule. + .build(); + TestBed.configureTestingModule(ngModule); + + // Extra configuration + TestBed.overrideTemplate( + MyComponent1, + 'If we need to tune testBed', + ); + TestBed.overrideTemplate(MyComponent2, 'More callbacks'); + + return TestBed.compileComponents(); + }); + + it('should render', inject( + [HttpBackend], + (httpBackend: HttpBackend) => { + const fixture = MockRender(MyComponent); + expect(fixture).toBeDefined(); + const content = fixture.nativeElement.innerHTML.replace( + //gm, + '', + ); + expect(content).toContain('
    My Content
    '); + + expect(content).toContain( + '
    MyComponent1: If we need to tune testBed
    ', + ); + expect(content).toContain( + '
    MyComponent2: More callbacks
    ', + ); + expect(content).toContain( + '
    MyComponent3:
    ', + ); + expect(content).toContain( + '
    ComponentWeDontWantToMimic: ComponentWeDontWantToMimic
    ', + ); + expect(content).toContain( + '
    ComponentWeWantToMimic:
    ', + ); + expect(content).toContain( + '
    ComponentStructural: -$implicit- b
    ', + ); + + expect(content).toContain( + '
    MyDirective:
    ', + ); + expect(content).toContain( + '
    DirectiveWeDontWantToMimic:
    ', + ); + expect(content).toContain( + 'DirectiveWeWantToMimic 1: render b', + ); + expect(content).toContain('DirectiveWeWantToMimic 2: render $'); + + expect(content).toContain('
    MyPipe: MyPipe:text:0
    '); + expect(content).toContain( + '
    PipeWeDontWantToMimic: PipeWeDontWantToMimic:text:0
    ', + ); + expect(content).toContain('
    PipeWeWantToMimic:
    '); + expect(content).toContain( + '
    PipeWeWantToCustomize: My Custom Result
    ', + ); + expect(content).toContain( + '
    PipeWeWantToRestore: PipeWeWantToRestore:text:0
    ', + ); + + expect(content).toContain( + '
    INJECTION_TOKEN_WE_DONT_WANT_TO_MIMIC: INJECTION_TOKEN_WE_DONT_WANT_TO_MIMIC
    ', + ); + expect(content).toContain( + '
    INJECTION_TOKEN_WE_WANT_TO_MIMIC:
    ', + ); + expect(content).toContain( + '
    INJECTION_TOKEN_WE_WANT_TO_CUSTOMIZE: My_Token
    ', + ); + + expect(content).toContain( + '
    anythingWeWant1: TheSameAsAnyProvider
    ', + ); + expect(content).toContain( + '
    anythingWeWant2: TheSameAsAnyProvider
    ', + ); + expect(content).toContain( + '
    myCustomProvider1: MyCustomProvider1
    ', + ); + expect(content).toContain( + '
    myCustomProvider2: MyCustomProvider2
    ', + ); + expect(content).toContain( + '
    myCustomProvider3: MyCustomProvider3
    ', + ); + + expect(content).toContain('
    myService1:
    '); + expect(content).toContain('
    myService2: MyService2
    '); + expect(content).toContain( + '
    serviceWeDontWantToMimic: ServiceWeDontWantToMimic
    ', + ); + expect(content).toContain( + '
    serviceWeWantToCustomize: My Customized String
    ', + ); + expect(content).toContain('
    serviceWeWantToMimic:
    '); + + // Checking that replacement works. + expect(httpBackend.constructor).toBeDefined(); + expect(httpBackend.constructor.name).toEqual( + 'HttpClientTestingBackend', + ); + }, + )); +}); diff --git a/examples/MockBuilder/test.promise.spec.ts b/examples/MockBuilder/test.promise.spec.ts new file mode 100644 index 0000000000..643eb38385 --- /dev/null +++ b/examples/MockBuilder/test.promise.spec.ts @@ -0,0 +1,37 @@ +import { MockBuilder, MockRender } from 'ng-mocks'; + +import { MyComponent1, MyComponent2 } from './fixtures.components'; + +describe('MockBuilder:promise', () => { + beforeEach(() => { + return ( + MockBuilder() + .keep(MyComponent1) + .keep(MyComponent2) + + // In case if you need extra customization of TestBed in promise way. + .beforeCompileComponents(testBed => { + testBed.overrideTemplate( + MyComponent1, + 'If we need to tune testBed', + ); + }) + .beforeCompileComponents(testBed => { + testBed.overrideTemplate(MyComponent2, 'More callbacks'); + }) + ); + }); + + it('should render content ignoring all dependencies', () => { + const fixture = MockRender( + '', + ); + expect(fixture).toBeDefined(); + expect(fixture.nativeElement.innerHTML).toContain( + 'If we need to tune testBed', + ); + expect(fixture.nativeElement.innerHTML).toContain( + 'More callbacks', + ); + }); +}); diff --git a/examples/MockBuilder/test.simple.spec.ts b/examples/MockBuilder/test.simple.spec.ts new file mode 100644 index 0000000000..2b994667c1 --- /dev/null +++ b/examples/MockBuilder/test.simple.spec.ts @@ -0,0 +1,23 @@ +import { MockBuilder, MockRender } from 'ng-mocks'; + +import { MyComponent } from './fixtures.components'; +import { MyModule } from './fixtures.modules'; + +describe('MockBuilder:simple', () => { + // Do not forget to return the promise of MockBuilder. + beforeEach(() => MockBuilder(MyComponent, MyModule)); + // The same as + // beforeEach(() => TestBed.configureTestingModule({{ + // imports: [MockModule(MyModule)], + // }).compileComponents()); + // but MyComponent has not been replaced with a mock copy for + // the testing purposes. + + it('should render content ignoring all dependencies', () => { + const fixture = MockRender(MyComponent); + expect(fixture).toBeDefined(); + expect(fixture.nativeElement.innerHTML).toContain( + '
    My Content
    ', + ); + }); +}); diff --git a/examples/MockBuilder/test.spec.ts b/examples/MockBuilder/test.spec.ts deleted file mode 100644 index c33f8bc42f..0000000000 --- a/examples/MockBuilder/test.spec.ts +++ /dev/null @@ -1,223 +0,0 @@ -import { HttpBackend, HttpClientModule } from '@angular/common/http'; -import { HttpClientTestingModule } from '@angular/common/http/testing'; -import { inject, TestBed } from '@angular/core/testing'; -import { MockBuilder, MockRender } from 'ng-mocks'; - -import { - ComponentContentChild, - ComponentWeDontWantToMimic, - ComponentWeWantToMimic, - MyComponent, - MyComponent1, - MyComponent2, - MyComponent3, -} from './fixtures.components'; -import { DirectiveWeDontWantToMimic, DirectiveWeWantToMimic, MyDirective } from './fixtures.directives'; -import { ModuleWeDontWantToMimic, ModuleWeWantToMimicBesidesMyModule, MyModule } from './fixtures.modules'; -import { - MyPipe, - PipeWeDontWantToMimicPipe, - PipeWeWantToCustomize, - PipeWeWantToMimicPipe, - PipeWeWantToRestore, -} from './fixtures.pipes'; -import { - AnythingWeWant1, - AnythingWeWant2, - MyCustomProvider1, - MyCustomProvider2, - MyCustomProvider3, - MyService1, - MyService2, - ServiceWeDontWantToMimic, - ServiceWeWantToCustomize, - ServiceWeWantToMimic, - TheSameAsAnyProvider, -} from './fixtures.services'; -import { - INJECTION_TOKEN_WE_DONT_WANT_TO_MIMIC, - INJECTION_TOKEN_WE_WANT_TO_CUSTOMIZE, - INJECTION_TOKEN_WE_WANT_TO_MIMIC, -} from './fixtures.tokens'; - -describe('MockBuilder:simple', () => { - beforeEach(() => MockBuilder(MyComponent, MyModule)); - // The same as - // beforeEach(() => TestBed.configureTestingModule({{ - // imports: [MockModule(MyModule)], - // }).compileComponents()); - // but MyComponent has not been replaced with a mock copy for - // the testing purposes. - - it('should render content ignoring all dependencies', () => { - const fixture = MockRender(MyComponent); - expect(fixture).toBeDefined(); - expect(fixture.debugElement.nativeElement.innerHTML).toContain('
    My Content
    '); - }); -}); - -describe('MockBuilder:deep', () => { - beforeEach(async () => { - const ngModule = MockBuilder(MyComponent, MyModule) - .mock(ComponentContentChild, { - render: { - block: { - $implicit: '-$implicit-', - variables: { a: { z: 'b' } }, - }, - }, - }) - - .keep(ModuleWeDontWantToMimic, { - dependency: true, - }) - .keep(ComponentWeDontWantToMimic, { - dependency: true, - }) - .keep(DirectiveWeDontWantToMimic, { - dependency: true, - }) - .keep(PipeWeDontWantToMimicPipe, { - dependency: true, - }) - .keep(ServiceWeDontWantToMimic) - .keep(INJECTION_TOKEN_WE_DONT_WANT_TO_MIMIC) - - // The same can be done with Components, Directives and Pipes. - // For Providers use .provider() or .mock(). - .replace(HttpClientModule, HttpClientTestingModule, { - dependency: true, - }) - - .mock(ModuleWeWantToMimicBesidesMyModule, { - dependency: true, - }) - .mock(ComponentWeWantToMimic, { - dependency: true, - }) - .mock(DirectiveWeWantToMimic, { - dependency: true, - render: { - $implicit: { a: '$' }, - variables: { a: { b: 'b' } }, - }, - }) - .mock(PipeWeWantToMimicPipe, { - dependency: true, - }) - .mock(ServiceWeWantToMimic) // makes all methods an empty function - .mock(INJECTION_TOKEN_WE_WANT_TO_MIMIC) // makes its value undefined - - .mock(PipeWeWantToCustomize, () => 'My Custom Result') - .mock(PipeWeWantToRestore, () => 'My Restored Pipe') - .mock(ServiceWeWantToCustomize, { getName: () => 'My Customized String' }) - .mock(INJECTION_TOKEN_WE_WANT_TO_CUSTOMIZE, 'My_Token') - - // All providers will be set into the TestModule. - .provide({ - provide: AnythingWeWant1, - useValue: new TheSameAsAnyProvider(), - }) - .provide({ - provide: AnythingWeWant2, - useFactory: () => new TheSameAsAnyProvider(), - }) - .provide(MyCustomProvider1) - .provide([MyCustomProvider2, MyCustomProvider3]) - - // Now the pipe won't be replaced with its mock copy. - .keep(PipeWeWantToRestore) - - // Extra configuration. - .keep(MyDirective) - .keep(MyPipe) - .mock(MyService1) - .keep(MyService2) - - // Even it belongs to the module that is marked as kept, - // the component will be replaced with its mock copy. - .mock(MyComponent3) - - // and now we want to build our NgModule. - .build(); - TestBed.configureTestingModule(ngModule); - - // Extra configuration - TestBed.overrideTemplate(MyComponent1, 'If we need to tune testBed'); - TestBed.overrideTemplate(MyComponent2, 'More callbacks'); - - return TestBed.compileComponents(); - }); - - it('should render', inject([HttpBackend], (httpBackend: HttpBackend) => { - const fixture = MockRender(MyComponent); - expect(fixture).toBeDefined(); - const content = fixture.debugElement.nativeElement.innerHTML.replace(//gm, ''); - expect(content).toContain('
    My Content
    '); - - expect(content).toContain('
    MyComponent1: If we need to tune testBed
    '); - expect(content).toContain('
    MyComponent2: More callbacks
    '); - expect(content).toContain('
    MyComponent3:
    '); - expect(content).toContain( - '
    ComponentWeDontWantToMimic: ComponentWeDontWantToMimic
    ', - ); - expect(content).toContain('
    ComponentWeWantToMimic:
    '); - expect(content).toContain('
    ComponentStructural: -$implicit- b
    '); - - expect(content).toContain('
    MyDirective:
    '); - expect(content).toContain('
    DirectiveWeDontWantToMimic:
    '); - expect(content).toContain('DirectiveWeWantToMimic 1: render b'); - expect(content).toContain('DirectiveWeWantToMimic 2: render $'); - - expect(content).toContain('
    MyPipe: MyPipe:text:0
    '); - expect(content).toContain('
    PipeWeDontWantToMimic: PipeWeDontWantToMimic:text:0
    '); - expect(content).toContain('
    PipeWeWantToMimic:
    '); - expect(content).toContain('
    PipeWeWantToCustomize: My Custom Result
    '); - expect(content).toContain('
    PipeWeWantToRestore: PipeWeWantToRestore:text:0
    '); - - expect(content).toContain( - '
    INJECTION_TOKEN_WE_DONT_WANT_TO_MIMIC: INJECTION_TOKEN_WE_DONT_WANT_TO_MIMIC
    ', - ); - expect(content).toContain('
    INJECTION_TOKEN_WE_WANT_TO_MIMIC:
    '); - expect(content).toContain('
    INJECTION_TOKEN_WE_WANT_TO_CUSTOMIZE: My_Token
    '); - - expect(content).toContain('
    anythingWeWant1: TheSameAsAnyProvider
    '); - expect(content).toContain('
    anythingWeWant2: TheSameAsAnyProvider
    '); - expect(content).toContain('
    myCustomProvider1: MyCustomProvider1
    '); - expect(content).toContain('
    myCustomProvider2: MyCustomProvider2
    '); - expect(content).toContain('
    myCustomProvider3: MyCustomProvider3
    '); - - expect(content).toContain('
    myService1:
    '); - expect(content).toContain('
    myService2: MyService2
    '); - expect(content).toContain('
    serviceWeDontWantToMimic: ServiceWeDontWantToMimic
    '); - expect(content).toContain('
    serviceWeWantToCustomize: My Customized String
    '); - expect(content).toContain('
    serviceWeWantToMimic:
    '); - - // Checking that replacement works. - expect(httpBackend.constructor).toBeDefined(); - expect(httpBackend.constructor.name).toEqual('HttpClientTestingBackend'); - })); -}); - -describe('MockBuilder:promise', () => { - beforeEach(() => - MockBuilder() - .keep(MyComponent1) - .keep(MyComponent2) - - // In case if you need extra customization of TestBed in promise way. - .beforeCompileComponents(testBed => { - testBed.overrideTemplate(MyComponent1, 'If we need to tune testBed'); - }) - .beforeCompileComponents(testBed => { - testBed.overrideTemplate(MyComponent2, 'More callbacks'); - }), - ); - - it('should render content ignoring all dependencies', () => { - const fixture = MockRender(''); - expect(fixture).toBeDefined(); - expect(fixture.debugElement.nativeElement.innerHTML).toContain('If we need to tune testBed'); - expect(fixture.debugElement.nativeElement.innerHTML).toContain('More callbacks'); - }); -}); diff --git a/examples/MockComponent/test.spec.ts b/examples/MockComponent/test.spec.ts index a9942b2211..b115566133 100644 --- a/examples/MockComponent/test.spec.ts +++ b/examples/MockComponent/test.spec.ts @@ -1,4 +1,11 @@ -import { Component, ContentChild, EventEmitter, Input, Output, TemplateRef } from '@angular/core'; +import { + Component, + ContentChild, + EventEmitter, + Input, + Output, + TemplateRef, +} from '@angular/core'; import { isMockOf, MockBuilder, MockRender, ngMocks } from 'ng-mocks'; import { staticFalse } from '../../tests'; @@ -8,7 +15,9 @@ import { staticFalse } from '../../tests'; template: `child`, }) class DependencyComponent { - @ContentChild('something', staticFalse) public injectedSomething: TemplateRef<{}> | undefined; + @ContentChild('something', staticFalse) public injectedSomething: + | TemplateRef<{}> + | undefined; @Input() public someInput = ''; @@ -19,7 +28,12 @@ class DependencyComponent { @Component({ selector: 'tested', - template: ` `, + template: ` + + `, }) class TestedComponent { public value = ''; @@ -27,7 +41,9 @@ class TestedComponent { } describe('MockComponent', () => { - beforeEach(() => MockBuilder(TestedComponent).mock(DependencyComponent)); + beforeEach(() => { + return MockBuilder(TestedComponent).mock(DependencyComponent); + }); it('sends the correct value to the child input', () => { const fixture = MockRender(TestedComponent); @@ -38,7 +54,9 @@ describe('MockComponent', () => { // By.css('app-child') // ).componentInstance // but properly typed. - const mockComponent = ngMocks.find(fixture, 'app-child').componentInstance; + const mockComponent = ngMocks.find( + 'app-child', + ).componentInstance; // Let's pretend that DependencyComponent has 'someInput' as // an input. TestedComponent sets its value via @@ -60,7 +78,8 @@ describe('MockComponent', () => { // By.directive(DependencyComponent) // ).componentInstance // but properly typed. - const mockComponent = ngMocks.find(fixture, DependencyComponent).componentInstance; + const mockComponent = ngMocks.find(DependencyComponent) + .componentInstance; // Again, let's pretend DependencyComponent has an output // called 'someOutput'. TestedComponent listens on the output via @@ -115,7 +134,8 @@ describe('MockComponent', () => { // The rendered template is wrapped by
    . // We can use this selector to assert exactly its content. - const mockNgTemplate = ngMocks.find(fixture.debugElement, '[data-key="something"]').nativeElement.innerHTML; + const mockNgTemplate = ngMocks.find('[data-key="something"]') + .nativeElement.innerHTML; expect(mockNgTemplate).toContain('

    inside template

    '); }); }); diff --git a/examples/MockDirective-Attribute/test.spec.ts b/examples/MockDirective-Attribute/test.spec.ts index 4dde242145..8f7412895b 100644 --- a/examples/MockDirective-Attribute/test.spec.ts +++ b/examples/MockDirective-Attribute/test.spec.ts @@ -1,4 +1,10 @@ -import { Component, Directive, EventEmitter, Input, Output } from '@angular/core'; +import { + Component, + Directive, + EventEmitter, + Input, + Output, +} from '@angular/core'; import { MockBuilder, MockRender, ngMocks } from 'ng-mocks'; @Directive({ @@ -14,7 +20,13 @@ class DependencyDirective { @Component({ selector: 'tested', - template: ` `, + template: ` + + `, }) class TestedComponent { public value = ''; @@ -22,7 +34,9 @@ class TestedComponent { } describe('MockDirective:Attribute', () => { - beforeEach(() => MockBuilder(TestedComponent).mock(DependencyDirective)); + beforeEach(() => { + return MockBuilder(TestedComponent).mock(DependencyDirective); + }); it('sends the correct value to the input', () => { const fixture = MockRender(TestedComponent); @@ -33,7 +47,10 @@ describe('MockDirective:Attribute', () => { // By.css('span') // ).injector.get(DependencyDirective) // but easier and more precise. - const mockDirective = ngMocks.get(ngMocks.find(fixture.debugElement, 'span'), DependencyDirective); + const mockDirective = ngMocks.get( + ngMocks.find('span'), + DependencyDirective, + ); // Let's pretend DependencyDirective has 'someInput' // as an input. TestedComponent sets its value via @@ -55,7 +72,10 @@ describe('MockDirective:Attribute', () => { // By.css('span') // ).injector.get(DependencyDirective) // but easier and more precise. - const mockDirective = ngMocks.get(ngMocks.find(fixture.debugElement, 'span'), DependencyDirective); + const mockDirective = ngMocks.get( + ngMocks.find('span'), + DependencyDirective, + ); // Again, let's pretend DependencyDirective has an output called // 'someOutput'. TestedComponent listens on the output via diff --git a/examples/MockDirective-Structural/test.spec.ts b/examples/MockDirective-Structural/test.spec.ts index 7e29c69215..1872f7810e 100644 --- a/examples/MockDirective-Structural/test.spec.ts +++ b/examples/MockDirective-Structural/test.spec.ts @@ -1,4 +1,10 @@ -import { Component, Directive, EventEmitter, Input, Output } from '@angular/core'; +import { + Component, + Directive, + EventEmitter, + Input, + Output, +} from '@angular/core'; import { isMockOf, MockBuilder, MockRender, ngMocks } from 'ng-mocks'; @Directive({ @@ -14,7 +20,11 @@ class DependencyDirective { @Component({ selector: 'tested', - template: ` content`, + template: ` content`, }) class TestedComponent { public value = ''; @@ -26,27 +36,29 @@ describe('MockDirective:Structural', () => { // Because they might require a context which should be provided. // Usually a developer knows the context and can render it // manually with proper setup. - beforeEach(() => - MockBuilder(TestedComponent).mock(DependencyDirective, { + beforeEach(() => { + return MockBuilder(TestedComponent).mock(DependencyDirective, { // render: true, // <-- a flag to render the directive by default - }), - ); + }); + }); it('renders content of the child structural directive', () => { const fixture = MockRender(TestedComponent); // Let's assert that nothing has been rendered inside of // the structural directive by default. - expect(fixture.debugElement.nativeElement.innerHTML).not.toContain('>content<'); + expect(fixture.nativeElement.innerHTML).not.toContain( + '>content<', + ); // And let's render it manually now. - const mockDirective = ngMocks.findInstance(fixture.debugElement, DependencyDirective); + const mockDirective = ngMocks.findInstance(DependencyDirective); if (isMockOf(mockDirective, DependencyDirective, 'd')) { mockDirective.__render(); fixture.detectChanges(); } // The content of the structural directive should be rendered. - expect(fixture.debugElement.nativeElement.innerHTML).toContain('>content<'); + expect(fixture.nativeElement.innerHTML).toContain('>content<'); }); }); diff --git a/examples/MockForms/test.spec.ts b/examples/MockForms/test.spec.ts index 111819429b..91b8ed5113 100644 --- a/examples/MockForms/test.spec.ts +++ b/examples/MockForms/test.spec.ts @@ -1,5 +1,9 @@ import { Component, forwardRef } from '@angular/core'; -import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms'; +import { + ControlValueAccessor, + FormsModule, + NG_VALUE_ACCESSOR, +} from '@angular/forms'; import { isMockOf, MockBuilder, MockRender, ngMocks } from 'ng-mocks'; @Component({ @@ -21,21 +25,31 @@ class DependencyComponent implements ControlValueAccessor { @Component({ selector: 'tested', - template: ` `, + template: ` + + `, }) class TestedComponent { public value: any; } describe('MockForms', () => { - beforeEach(() => MockBuilder(TestedComponent).mock(DependencyComponent).keep(FormsModule)); + beforeEach(() => { + return MockBuilder(TestedComponent) + .mock(DependencyComponent) + .keep(FormsModule); + }); it('sends the correct value to the mock form component', async () => { const fixture = MockRender(TestedComponent); const component = fixture.point.componentInstance; // Let's find the mock form component. - const mockControl = ngMocks.find(fixture.debugElement, DependencyComponent).componentInstance; + const mockControl = ngMocks.find(DependencyComponent) + .componentInstance; // Let's simulate its change, like a user does it. if (isMockOf(mockControl, DependencyComponent, 'c')) { diff --git a/examples/MockInstance/test.spec.ts b/examples/MockInstance/test.spec.ts index 2f491ad8a7..c516ade8b0 100644 --- a/examples/MockInstance/test.spec.ts +++ b/examples/MockInstance/test.spec.ts @@ -1,5 +1,16 @@ -import { AfterViewInit, Component, Injector, ViewChild } from '@angular/core'; -import { MockBuilder, MockInstance, MockRender, MockReset, ngMocks } from 'ng-mocks'; +import { + AfterViewInit, + Component, + Injector, + ViewChild, +} from '@angular/core'; +import { + MockBuilder, + MockInstance, + MockRender, + MockReset, + ngMocks, +} from 'ng-mocks'; import { Observable, Subject } from 'rxjs'; // A child component that contains update$ the parent component wants to listen to. @@ -38,6 +49,7 @@ class RealComponent implements AfterViewInit { describe('MockInstance', () => { // A normal setup of the TestBed, TargetComponent will be replaced // with its mock copy. + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(RealComponent).mock(ChildComponent)); beforeAll(() => { @@ -64,6 +76,6 @@ describe('MockInstance', () => { it('should render', () => { // Without the custom initialization rendering would fail here // with "Cannot read property 'subscribe' of undefined". - expect(() => MockRender(RealComponent)).not.toThrowError(/Cannot read property 'subscribe' of undefined/); + expect(() => MockRender(RealComponent)).not.toThrow(); }); }); diff --git a/examples/MockModule/test.spec.ts b/examples/MockModule/test.spec.ts index 7a4141c488..6d1abd35a0 100644 --- a/examples/MockModule/test.spec.ts +++ b/examples/MockModule/test.spec.ts @@ -1,5 +1,13 @@ import { CommonModule } from '@angular/common'; -import { Component, ContentChild, EventEmitter, Input, NgModule, Output, TemplateRef } from '@angular/core'; +import { + Component, + ContentChild, + EventEmitter, + Input, + NgModule, + Output, + TemplateRef, +} from '@angular/core'; import { MockBuilder, MockRender } from 'ng-mocks'; import { staticFalse } from '../../tests'; @@ -28,7 +36,12 @@ class DependencyModule {} @Component({ selector: 'tested', - template: ` `, + template: ` + + `, }) class TestedComponent { public value = ''; @@ -36,7 +49,9 @@ class TestedComponent { } describe('MockModule', () => { - beforeEach(() => MockBuilder(TestedComponent).mock(DependencyModule)); + beforeEach(() => { + return MockBuilder(TestedComponent).mock(DependencyModule); + }); it('renders TestedComponent with its dependencies', () => { const fixture = MockRender(TestedComponent); diff --git a/examples/MockObservable/test.spec.ts b/examples/MockObservable/test.spec.ts index eb19b70c8e..575fa1b1f0 100644 --- a/examples/MockObservable/test.spec.ts +++ b/examples/MockObservable/test.spec.ts @@ -1,6 +1,12 @@ import { CommonModule } from '@angular/common'; import { Component, Injectable, NgModule } from '@angular/core'; -import { MockBuilder, MockInstance, MockRender, ngMocks } from 'ng-mocks'; +import { TestBed } from '@angular/core/testing'; +import { + MockBuilder, + MockInstance, + MockRender, + ngMocks, +} from 'ng-mocks'; import { Observable, Subject } from 'rxjs'; // A simple service, might have contained more logic, @@ -8,6 +14,10 @@ import { Observable, Subject } from 'rxjs'; @Injectable() class TargetService { public readonly value$: Observable = new Observable(); + + public getValue$(): Observable { + return this.value$; + } } @Component({ @@ -33,6 +43,7 @@ describe('MockObservable', () => { // Because we want to test the component, we pass it as the first // parameter of MockBuilder. To create its mock dependencies // we pass its module as the second parameter. + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(TargetComponent, TargetModule)); // Now we need to customize the mock copy of the service. @@ -79,5 +90,10 @@ describe('MockObservable', () => { expect(fixture.nativeElement.innerHTML).not.toContain('1'); expect(fixture.nativeElement.innerHTML).not.toContain('2'); expect(fixture.nativeElement.innerHTML).not.toContain('3'); + + // Checking that a sibling method has been replaced + // with a mock copy too. + expect(TestBed.get(TargetService).getValue$).toBeDefined(); + expect(TestBed.get(TargetService).getValue$()).toBeUndefined(); }); }); diff --git a/examples/MockPipe/test.spec.ts b/examples/MockPipe/test.spec.ts index 8022631ae7..b843834c5c 100644 --- a/examples/MockPipe/test.spec.ts +++ b/examples/MockPipe/test.spec.ts @@ -1,5 +1,5 @@ import { Component, Pipe, PipeTransform } from '@angular/core'; -import { MockBuilder, MockRender, ngMocks } from 'ng-mocks'; +import { MockBuilder, MockRender } from 'ng-mocks'; @Pipe({ name: 'dependency' }) class DependencyPipe implements PipeTransform { @@ -7,18 +7,24 @@ class DependencyPipe implements PipeTransform { } @Component({ - selector: 'tested', - template: ` {{ 'foo' | dependency }} `, + selector: 'component', + template: `{{ 'foo' | dependency }}`, }) class TestedComponent {} describe('MockPipe', () => { - beforeEach(() => MockBuilder(TestedComponent).mock(DependencyPipe, (...args: string[]) => JSON.stringify(args))); + beforeEach(() => { + return MockBuilder(TestedComponent).mock( + DependencyPipe, + (...args: string[]) => JSON.stringify(args), + ); + }); it('transforms values to json', () => { const fixture = MockRender(TestedComponent); - const pipeElement = ngMocks.find(fixture.debugElement, 'span'); - expect(pipeElement.nativeElement.innerHTML).toEqual('["foo"]'); + expect(fixture.nativeElement.innerHTML).toEqual( + '["foo"]', + ); }); }); diff --git a/examples/MockProvider/test.spec.ts b/examples/MockProvider/test.spec.ts index c3e7646542..766608d02a 100644 --- a/examples/MockProvider/test.spec.ts +++ b/examples/MockProvider/test.spec.ts @@ -1,11 +1,18 @@ import { CommonModule } from '@angular/common'; -import { Component, Inject, Injectable, InjectionToken } from '@angular/core'; +import { + Component, + Inject, + Injectable, + InjectionToken, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { MockProvider } from 'ng-mocks'; const UNK_TOKEN = new InjectionToken('UNK_TOKEN'); const STR_TOKEN = new InjectionToken('STR_TOKEN'); -const OBJ_TOKEN = new InjectionToken<{ name: string; value: number }>('OBJ_TOKEN'); +const OBJ_TOKEN = new InjectionToken<{ name: string; value: number }>( + 'OBJ_TOKEN', +); @Injectable() class Dependency1Service { @@ -27,7 +34,11 @@ class Dependency2Service { @Component({ selector: 'target', - template: `"{{ dep1.name }}" "{{ dep2.name }}" "{{ unk }}" "{{ pri }}" "{{ str }}" "{{ obj | json }}"`, + template: ` + "{{ dep1.name }}" "{{ dep2.name }}" "{{ unk }}" "{{ pri }}" "{{ + str + }}" "{{ obj | json }}" + `, }) class TargetComponent { public constructor( @@ -63,9 +74,15 @@ describe('MockProvider', () => { mockObj.value = 321; const fixture = TestBed.createComponent(TargetComponent); fixture.detectChanges(); - expect(fixture.debugElement.injector.get(Dependency1Service).echo()).toBeUndefined(); - expect(fixture.debugElement.injector.get(Dependency2Service).echo()).toBeUndefined(); - expect(fixture.debugElement.injector.get(OBJ_TOKEN)).toBe(mockObj as any); + expect( + fixture.debugElement.injector.get(Dependency1Service).echo(), + ).toBeUndefined(); + expect( + fixture.debugElement.injector.get(Dependency2Service).echo(), + ).toBeUndefined(); + expect(fixture.debugElement.injector.get(OBJ_TOKEN)).toBe( + mockObj as any, + ); expect(fixture.nativeElement.innerHTML).not.toContain('"target"'); expect(fixture.nativeElement.innerHTML).toContain('"d2:mock"'); expect(fixture.nativeElement.innerHTML).toContain('"mock token"'); diff --git a/examples/MockReactiveForms/test.spec.ts b/examples/MockReactiveForms/test.spec.ts index 704d8bd9d4..06edeb32ce 100644 --- a/examples/MockReactiveForms/test.spec.ts +++ b/examples/MockReactiveForms/test.spec.ts @@ -1,5 +1,10 @@ import { Component, forwardRef } from '@angular/core'; -import { ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR, ReactiveFormsModule } from '@angular/forms'; +import { + ControlValueAccessor, + FormControl, + NG_VALUE_ACCESSOR, + ReactiveFormsModule, +} from '@angular/forms'; import { isMockOf, MockBuilder, MockRender, ngMocks } from 'ng-mocks'; @Component({ @@ -28,14 +33,19 @@ class TestedComponent { } describe('MockReactiveForms', () => { - beforeEach(() => MockBuilder(TestedComponent).mock(DependencyComponent).keep(ReactiveFormsModule)); + beforeEach(() => { + return MockBuilder(TestedComponent) + .mock(DependencyComponent) + .keep(ReactiveFormsModule); + }); it('sends the correct value to the mock form component', () => { const fixture = MockRender(TestedComponent); const component = fixture.point.componentInstance; // Let's find the mock form component. - const mockControl = ngMocks.find(fixture.debugElement, DependencyComponent).componentInstance; + const mockControl = ngMocks.find(DependencyComponent) + .componentInstance; // Let's simulate its change, like a user does it. if (isMockOf(mockControl, DependencyComponent, 'c')) { diff --git a/examples/MockRender/test.spec.ts b/examples/MockRender/test.spec.ts index b9c681c2db..12a3c3f02e 100644 --- a/examples/MockRender/test.spec.ts +++ b/examples/MockRender/test.spec.ts @@ -1,5 +1,15 @@ +// tslint:disable strict-type-predicates + import { CommonModule } from '@angular/common'; -import { Component, ContentChild, EventEmitter, Input, NgModule, Output, TemplateRef } from '@angular/core'; +import { + Component, + ContentChild, + EventEmitter, + Input, + NgModule, + Output, + TemplateRef, +} from '@angular/core'; import { MockBuilder, MockRender, ngMocks } from 'ng-mocks'; import { staticFalse } from '../../tests'; @@ -9,7 +19,8 @@ import { staticFalse } from '../../tests'; template: `dependency`, }) class DependencyComponent { - @ContentChild('something', staticFalse) public injectedSomething?: TemplateRef<{}>; + @ContentChild('something', staticFalse) + public injectedSomething?: TemplateRef<{}>; @Input() public someInput = ''; @Output() public readonly someOutput = new EventEmitter(); } @@ -22,7 +33,12 @@ class DependencyModule {} @Component({ selector: 'tested', - template: ` `, + template: ` + + `, }) class TestedComponent { @Output() public readonly trigger = new EventEmitter(); @@ -31,10 +47,12 @@ class TestedComponent { } describe('MockRender', () => { + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(TestedComponent, DependencyModule)); it('renders template', () => { - const spy = jasmine.createSpy(); + const spy = + typeof jest === 'undefined' ? jasmine.createSpy() : jest.fn(); // in case of jest // const spy = jest.fn(); @@ -59,7 +77,9 @@ describe('MockRender', () => { // ngMocks.input helps to get the current value of an input on // a related debugElement without knowing its owner. - expect(ngMocks.input(fixture.point, 'value1')).toEqual('something1'); + expect(ngMocks.input(fixture.point, 'value1')).toEqual( + 'something1', + ); expect(ngMocks.input(fixture.point, 'value2')).toEqual('check'); // ngMocks.output does the same with outputs. @@ -68,7 +88,11 @@ describe('MockRender', () => { }); it('renders inputs and outputs automatically', () => { - const spy = jasmine.createSpy(); + const spy = + typeof jest === 'undefined' ? jasmine.createSpy() : jest.fn(); + // in case of jest + // const logoClickSpy = jest.fn(); + // Generates a template like: // . @@ -78,7 +102,9 @@ describe('MockRender', () => { }); // Checking the inputs. - expect(ngMocks.input(fixture.point, 'value1')).toEqual('something2'); + expect(ngMocks.input(fixture.point, 'value1')).toEqual( + 'something2', + ); expect(ngMocks.input(fixture.point, 'value2')).toBeUndefined(); // Checking the outputs. diff --git a/examples/NG_MOCKS/NG_MOCKS.spec.ts b/examples/NG_MOCKS/NG_MOCKS.spec.ts index 237bec92de..d40995b1ff 100644 --- a/examples/NG_MOCKS/NG_MOCKS.spec.ts +++ b/examples/NG_MOCKS/NG_MOCKS.spec.ts @@ -11,10 +11,25 @@ import { MyComponent2, MyComponent3, } from './fixtures.components'; -import { DirectiveWeDontWantToMimic, DirectiveWeWantToMimic } from './fixtures.directives'; -import { ModuleWeDontWantToMimic, ModuleWeWantToMimicBesidesMyModule, MyModule } from './fixtures.modules'; -import { PipeWeWantToRestore, WeDontWantToMimicPipe, WeWantToMimicPipe } from './fixtures.pipes'; -import { ServiceWeDontWantToMimic, ServiceWeWantToCustomize, ServiceWeWantToMimic } from './fixtures.services'; +import { + DirectiveWeDontWantToMimic, + DirectiveWeWantToMimic, +} from './fixtures.directives'; +import { + ModuleWeDontWantToMimic, + ModuleWeWantToMimicBesidesMyModule, + MyModule, +} from './fixtures.modules'; +import { + PipeWeWantToRestore, + WeDontWantToMimicPipe, + WeWantToMimicPipe, +} from './fixtures.pipes'; +import { + ServiceWeDontWantToMimic, + ServiceWeWantToCustomize, + ServiceWeWantToMimic, +} from './fixtures.services'; import { INJECTION_TOKEN_WE_DONT_WANT_TO_MIMIC, INJECTION_TOKEN_WE_WANT_TO_CUSTOMIZE, @@ -40,7 +55,9 @@ describe('NG_MOCKS:deep', () => { .mock(ServiceWeWantToMimic) // makes all methods an empty function .mock(INJECTION_TOKEN_WE_WANT_TO_MIMIC) // makes its value undefined - .mock(ServiceWeWantToCustomize, { getName: () => 'My Customized String' }) + .mock(ServiceWeWantToCustomize, { + getName: () => 'My Customized String', + }) .mock(INJECTION_TOKEN_WE_WANT_TO_CUSTOMIZE, 'My_Token') // Now the pipe won't be replaced with its mock copy. @@ -55,72 +72,134 @@ describe('NG_MOCKS:deep', () => { TestBed.configureTestingModule(ngModule); // Extra configuration - TestBed.overrideTemplate(MyComponent1, 'If we need to tune testBed'); + TestBed.overrideTemplate( + MyComponent1, + 'If we need to tune testBed', + ); TestBed.overrideTemplate(MyComponent2, 'More callbacks'); return TestBed.compileComponents(); }); - it('should contain mocks', inject([NG_MOCKS], (mocks: Map) => { - // main part - const myComponent = mocks.get(MyComponent); - expect(myComponent).toBe(MyComponent); - const myModule = mocks.get(MyModule); - expect(isMockedNgDefOf(myModule, MyModule, 'm')).toBeTruthy(); - - // keep - const componentWeDontWantToMimic = mocks.get(ComponentWeDontWantToMimic); - expect(componentWeDontWantToMimic).toBe(ComponentWeDontWantToMimic); - const directiveWeDontWantToMimic = mocks.get(DirectiveWeDontWantToMimic); - expect(directiveWeDontWantToMimic).toBe(DirectiveWeDontWantToMimic); - const pipeWeDontWantToMimic = mocks.get(WeDontWantToMimicPipe); - expect(pipeWeDontWantToMimic).toBe(WeDontWantToMimicPipe); - const serviceWeDontWantToMimic = mocks.get(ServiceWeDontWantToMimic); - expect(serviceWeDontWantToMimic).toBe(ServiceWeDontWantToMimic); - const injectionTokenWeDontWantToMimic = mocks.get(INJECTION_TOKEN_WE_DONT_WANT_TO_MIMIC); - expect(injectionTokenWeDontWantToMimic).toBe(INJECTION_TOKEN_WE_DONT_WANT_TO_MIMIC); - - // replace - const httpClientModule = mocks.get(HttpClientModule); - expect(httpClientModule).toBe(HttpClientTestingModule); - - // mimic - const moduleWeWantToMimicBesidesMyModule = mocks.get(ModuleWeWantToMimicBesidesMyModule); - expect(isMockedNgDefOf(moduleWeWantToMimicBesidesMyModule, ModuleWeWantToMimicBesidesMyModule, 'm')).toBeTruthy(); - const componentWeWantToMimic = mocks.get(ComponentWeWantToMimic); - expect(isMockedNgDefOf(componentWeWantToMimic, ComponentWeWantToMimic, 'c')).toBeTruthy(); - const directiveWeWantToMimic = mocks.get(DirectiveWeWantToMimic); - expect(isMockedNgDefOf(directiveWeWantToMimic, DirectiveWeWantToMimic, 'd')).toBeTruthy(); - const pipeWeWantToMimic = mocks.get(WeWantToMimicPipe); - expect(isMockedNgDefOf(pipeWeWantToMimic, WeWantToMimicPipe, 'p')).toBeTruthy(); - const serviceWeWantToMimic = mocks.get(ServiceWeWantToMimic); - expect(serviceWeWantToMimic).toBeDefined(); - expect(serviceWeWantToMimic.useFactory).toBeDefined(); - const serviceWeWantToMimicInstance = serviceWeWantToMimic.useFactory(); - expect(serviceWeWantToMimicInstance.getName).toBeDefined(); - expect(serviceWeWantToMimicInstance.getName()).toBeUndefined(); - expect(mocks.has(INJECTION_TOKEN_WE_WANT_TO_MIMIC)).toBeDefined(); - expect(mocks.get(INJECTION_TOKEN_WE_WANT_TO_MIMIC)).toBeUndefined(); - - // customize - const serviceWeWantToCustomize = mocks.get(ServiceWeWantToCustomize); - expect(serviceWeWantToCustomize).toBeDefined(); - expect(serviceWeWantToCustomize.useFactory).toBeDefined(); - const serviceWeWantToCustomizeInstance = serviceWeWantToCustomize.useFactory(); - expect(serviceWeWantToCustomizeInstance.getName).toBeDefined(); - expect(serviceWeWantToCustomizeInstance.getName()).toEqual('My Customized String'); - const injectionTokenWeWantToCustomize = mocks.get(INJECTION_TOKEN_WE_WANT_TO_CUSTOMIZE); - expect(injectionTokenWeWantToCustomize).toBeDefined(); - expect(injectionTokenWeWantToCustomize.useFactory).toBeDefined(); - const injectionTokenWeWantToCustomizeInstance = injectionTokenWeWantToCustomize.useFactory(); - expect(injectionTokenWeWantToCustomizeInstance).toEqual('My_Token'); - - // restore - const pipeWeWantToRestore = mocks.get(PipeWeWantToRestore); - expect(pipeWeWantToRestore).toBe(PipeWeWantToRestore); - - // mimicked nested - const myComponent3 = mocks.get(MyComponent3); - expect(isMockedNgDefOf(myComponent3, MyComponent3, 'c')).toBeTruthy(); - })); + it('should contain mocks', inject( + [NG_MOCKS], + (mocks: Map) => { + // main part + const myComponent = mocks.get(MyComponent); + expect(myComponent).toBe(MyComponent); + const myModule = mocks.get(MyModule); + expect(isMockedNgDefOf(myModule, MyModule, 'm')).toBeTruthy(); + + // keep + const componentWeDontWantToMimic = mocks.get( + ComponentWeDontWantToMimic, + ); + expect(componentWeDontWantToMimic).toBe( + ComponentWeDontWantToMimic, + ); + const directiveWeDontWantToMimic = mocks.get( + DirectiveWeDontWantToMimic, + ); + expect(directiveWeDontWantToMimic).toBe( + DirectiveWeDontWantToMimic, + ); + const pipeWeDontWantToMimic = mocks.get(WeDontWantToMimicPipe); + expect(pipeWeDontWantToMimic).toBe(WeDontWantToMimicPipe); + const serviceWeDontWantToMimic = mocks.get( + ServiceWeDontWantToMimic, + ); + expect(serviceWeDontWantToMimic).toBe(ServiceWeDontWantToMimic); + const injectionTokenWeDontWantToMimic = mocks.get( + INJECTION_TOKEN_WE_DONT_WANT_TO_MIMIC, + ); + expect(injectionTokenWeDontWantToMimic).toBe( + INJECTION_TOKEN_WE_DONT_WANT_TO_MIMIC, + ); + + // replace + const httpClientModule = mocks.get(HttpClientModule); + expect(httpClientModule).toBe(HttpClientTestingModule); + + // mimic + const moduleWeWantToMimicBesidesMyModule = mocks.get( + ModuleWeWantToMimicBesidesMyModule, + ); + expect( + isMockedNgDefOf( + moduleWeWantToMimicBesidesMyModule, + ModuleWeWantToMimicBesidesMyModule, + 'm', + ), + ).toBeTruthy(); + const componentWeWantToMimic = mocks.get( + ComponentWeWantToMimic, + ); + expect( + isMockedNgDefOf( + componentWeWantToMimic, + ComponentWeWantToMimic, + 'c', + ), + ).toBeTruthy(); + const directiveWeWantToMimic = mocks.get( + DirectiveWeWantToMimic, + ); + expect( + isMockedNgDefOf( + directiveWeWantToMimic, + DirectiveWeWantToMimic, + 'd', + ), + ).toBeTruthy(); + const pipeWeWantToMimic = mocks.get(WeWantToMimicPipe); + expect( + isMockedNgDefOf(pipeWeWantToMimic, WeWantToMimicPipe, 'p'), + ).toBeTruthy(); + const serviceWeWantToMimic = mocks.get(ServiceWeWantToMimic); + expect(serviceWeWantToMimic).toBeDefined(); + expect(serviceWeWantToMimic.useFactory).toBeDefined(); + const serviceWeWantToMimicInstance = serviceWeWantToMimic.useFactory(); + expect(serviceWeWantToMimicInstance.getName).toBeDefined(); + expect(serviceWeWantToMimicInstance.getName()).toBeUndefined(); + expect( + mocks.has(INJECTION_TOKEN_WE_WANT_TO_MIMIC), + ).toBeDefined(); + expect( + mocks.get(INJECTION_TOKEN_WE_WANT_TO_MIMIC), + ).toBeUndefined(); + + // customize + const serviceWeWantToCustomize = mocks.get( + ServiceWeWantToCustomize, + ); + expect(serviceWeWantToCustomize).toBeDefined(); + expect(serviceWeWantToCustomize.useFactory).toBeDefined(); + const serviceWeWantToCustomizeInstance = serviceWeWantToCustomize.useFactory(); + expect(serviceWeWantToCustomizeInstance.getName).toBeDefined(); + expect(serviceWeWantToCustomizeInstance.getName()).toEqual( + 'My Customized String', + ); + const injectionTokenWeWantToCustomize = mocks.get( + INJECTION_TOKEN_WE_WANT_TO_CUSTOMIZE, + ); + expect(injectionTokenWeWantToCustomize).toBeDefined(); + expect( + injectionTokenWeWantToCustomize.useFactory, + ).toBeDefined(); + const injectionTokenWeWantToCustomizeInstance = injectionTokenWeWantToCustomize.useFactory(); + expect(injectionTokenWeWantToCustomizeInstance).toEqual( + 'My_Token', + ); + + // restore + const pipeWeWantToRestore = mocks.get(PipeWeWantToRestore); + expect(pipeWeWantToRestore).toBe(PipeWeWantToRestore); + + // mimicked nested + const myComponent3 = mocks.get(MyComponent3); + expect( + isMockedNgDefOf(myComponent3, MyComponent3, 'c'), + ).toBeTruthy(); + }, + )); }); diff --git a/examples/TestAttributeDirective/test.spec.ts b/examples/TestAttributeDirective/test.spec.ts index 2970a6aa43..fb0544c149 100644 --- a/examples/TestAttributeDirective/test.spec.ts +++ b/examples/TestAttributeDirective/test.spec.ts @@ -1,4 +1,9 @@ -import { Directive, ElementRef, HostListener, Input } from '@angular/core'; +import { + Directive, + ElementRef, + HostListener, + Input, +} from '@angular/core'; import { MockBuilder, MockRender, ngMocks } from 'ng-mocks'; // The purpose of the directive is to add a background color @@ -27,6 +32,7 @@ describe('TestAttributeDirective', () => { // Because we want to test the directive, we pass it as the first // parameter of MockBuilder. We can omit the second parameter, // because there are no dependencies. + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(TargetDirective)); it('uses default background color', () => { @@ -34,7 +40,9 @@ describe('TestAttributeDirective', () => { // By default, without the mouse enter, there is no background // color on the div. - expect(fixture.nativeElement.innerHTML).not.toContain('style="background-color: yellow;"'); + expect(fixture.nativeElement.innerHTML).not.toContain( + 'style="background-color: yellow;"', + ); // Let's simulate the mouse enter event. // fixture.point is out root element from the rendered template, @@ -43,13 +51,17 @@ describe('TestAttributeDirective', () => { fixture.point.triggerEventHandler('mouseenter', null); // Let's assert the color. - expect(fixture.nativeElement.innerHTML).toContain('style="background-color: yellow;"'); + expect(fixture.nativeElement.innerHTML).toContain( + 'style="background-color: yellow;"', + ); // Now let's simulate the mouse mouse leave event. fixture.point.triggerEventHandler('mouseleave', null); // And assert that the background color is gone now. - expect(fixture.nativeElement.innerHTML).not.toContain('style="background-color: yellow;"'); + expect(fixture.nativeElement.innerHTML).not.toContain( + 'style="background-color: yellow;"', + ); }); it('sets provided background color', () => { @@ -63,13 +75,17 @@ describe('TestAttributeDirective', () => { // Let's assert that the background color is red. fixture.point.triggerEventHandler('mouseenter', null); - expect(fixture.nativeElement.innerHTML).toContain('style="background-color: red;"'); + expect(fixture.nativeElement.innerHTML).toContain( + 'style="background-color: red;"', + ); // Let's switch the color, we don't need `.point`, because we // access a middle component of MockRender. fixture.componentInstance.color = 'blue'; fixture.detectChanges(); // shaking the template fixture.point.triggerEventHandler('mouseenter', null); - expect(fixture.nativeElement.innerHTML).toContain('style="background-color: blue;"'); + expect(fixture.nativeElement.innerHTML).toContain( + 'style="background-color: blue;"', + ); }); }); diff --git a/examples/TestHttpInterceptor/test.spec.ts b/examples/TestHttpInterceptor/test.spec.ts index 642b133dd6..9756da7fac 100644 --- a/examples/TestHttpInterceptor/test.spec.ts +++ b/examples/TestHttpInterceptor/test.spec.ts @@ -7,7 +7,10 @@ import { HttpRequest, HTTP_INTERCEPTORS, } from '@angular/common/http'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { + HttpClientTestingModule, + HttpTestingController, +} from '@angular/common/http/testing'; import { Injectable, NgModule } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { MockBuilder, NG_MOCKS_INTERCEPTORS } from 'ng-mocks'; @@ -18,7 +21,10 @@ import { Observable } from 'rxjs'; class TargetInterceptor implements HttpInterceptor { protected value = 'HttpInterceptor'; - public intercept(request: HttpRequest, next: HttpHandler): Observable> { + public intercept( + request: HttpRequest, + next: HttpHandler, + ): Observable> { return next.handle( request.clone({ setHeaders: { @@ -34,7 +40,10 @@ class TargetInterceptor implements HttpInterceptor { class MockInterceptor implements HttpInterceptor { protected value = 'Ignore'; - public intercept(request: HttpRequest, next: HttpHandler): Observable> { + public intercept( + request: HttpRequest, + next: HttpHandler, + ): Observable> { return next.handle( request.clone({ setHeaders: { @@ -71,16 +80,18 @@ describe('TestHttpInterceptor', () => { // we need to pass its module as the second parameter. Also we // should to pass HTTP_INTERCEPTORS into `.mock` and replace // HttpClientModule with HttpClientTestingModule. - beforeEach(() => - MockBuilder(TargetInterceptor, TargetModule) + beforeEach(() => { + return MockBuilder(TargetInterceptor, TargetModule) .exclude(NG_MOCKS_INTERCEPTORS) .keep(HTTP_INTERCEPTORS) - .replace(HttpClientModule, HttpClientTestingModule), - ); + .replace(HttpClientModule, HttpClientTestingModule); + }); it('triggers interceptor', () => { const client: HttpClient = TestBed.get(HttpClient); - const httpMock: HttpTestingController = TestBed.get(HttpTestingController); + const httpMock: HttpTestingController = TestBed.get( + HttpTestingController, + ); // Let's do a simply request. client.get('/target').subscribe(); @@ -90,6 +101,8 @@ describe('TestHttpInterceptor', () => { req.flush(''); httpMock.verify(); - expect(req.request.headers.get('My-Custom')).toEqual('HttpInterceptor'); + expect(req.request.headers.get('My-Custom')).toEqual( + 'HttpInterceptor', + ); }); }); diff --git a/examples/TestHttpRequest/test.spec.ts b/examples/TestHttpRequest/test.spec.ts index 4e5a241946..3517878d07 100644 --- a/examples/TestHttpRequest/test.spec.ts +++ b/examples/TestHttpRequest/test.spec.ts @@ -1,5 +1,8 @@ import { HttpClient, HttpClientModule } from '@angular/common/http'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { + HttpClientTestingModule, + HttpTestingController, +} from '@angular/common/http/testing'; import { Injectable, NgModule } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { MockBuilder } from 'ng-mocks'; @@ -28,12 +31,19 @@ describe('TestHttpRequest', () => { // initialization, we need to pass its module as the second // parameter. And, the last but not the least, we need to replace // HttpClientModule with HttpClientTestingModule. - beforeEach(() => MockBuilder(TargetService, TargetModule).replace(HttpClientModule, HttpClientTestingModule)); + beforeEach(() => { + return MockBuilder(TargetService, TargetModule).replace( + HttpClientModule, + HttpClientTestingModule, + ); + }); it('sends a request', () => { // Let's extract the service and http controller for testing. const service: TargetService = TestBed.get(TargetService); - const httpMock: HttpTestingController = TestBed.get(HttpTestingController); + const httpMock: HttpTestingController = TestBed.get( + HttpTestingController, + ); // A simple subscription to check what the service returns. let actual: any; diff --git a/examples/TestLifecycleHooks/test.spec.ts b/examples/TestLifecycleHooks/test.spec.ts index 278e88f654..23f6197344 100644 --- a/examples/TestLifecycleHooks/test.spec.ts +++ b/examples/TestLifecycleHooks/test.spec.ts @@ -59,7 +59,14 @@ class TargetService { template: ``, }) class TargetComponent - implements OnInit, OnDestroy, OnChanges, AfterViewInit, AfterViewChecked, AfterContentInit, AfterContentChecked { + implements + OnInit, + OnDestroy, + OnChanges, + AfterViewInit, + AfterViewChecked, + AfterContentInit, + AfterContentChecked { @Input() public input: string | null = null; public constructor(protected readonly service: TargetService) { @@ -105,6 +112,7 @@ class TargetModule {} describe('TestLifecycleHooks', () => { ngMocks.faster(); + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(TargetComponent, TargetModule)); it('triggers lifecycle hooks correctly via MockRender', () => { @@ -146,7 +154,8 @@ describe('TestLifecycleHooks', () => { fixture.componentInstance.input = 'change'; fixture.detectChanges(); - // Only OnChange, AfterViewChecked, AfterContentChecked should be triggered. + // Only OnChange, AfterViewChecked, AfterContentChecked + // should be triggered. expect(service.ctor).toHaveBeenCalledTimes(1); expect(service.onInit).toHaveBeenCalledTimes(1); expect(service.onDestroy).toHaveBeenCalledTimes(0); diff --git a/examples/TestMultiToken/test.spec.ts b/examples/TestMultiToken/test.spec.ts index e5eb38886f..0e2813f34e 100644 --- a/examples/TestMultiToken/test.spec.ts +++ b/examples/TestMultiToken/test.spec.ts @@ -45,6 +45,7 @@ describe('TestMultiToken', () => { // Because we want to test the token, we pass it as the first // parameter of MockBuilder. To correctly satisfy its initialization // we need to pass its module as the second parameter. + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(TOKEN_MULTI, TargetModule)); it('creates TOKEN_MULTI', () => { @@ -58,7 +59,8 @@ describe('TestMultiToken', () => { expect(tokens[0].name).toEqual('class'); // Verifying that the token is an instance of ServiceExisting. - // But because it has been replaced with its mock copy we should see an empty name. + // But because it has been replaced with its mock copy + // we should see an empty name. expect(tokens[1]).toEqual(jasmine.any(ServiceExisting)); expect(tokens[1].name).toBeUndefined(); diff --git a/examples/TestPipe/test.spec.ts b/examples/TestPipe/test.spec.ts index 473182540f..79079c1398 100644 --- a/examples/TestPipe/test.spec.ts +++ b/examples/TestPipe/test.spec.ts @@ -23,6 +23,7 @@ describe('TestPipe', () => { // Because we want to test the pipe, we pass it as the first // parameter of MockBuilder. We can omit the second parameter, // because there are no dependencies. + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(TargetPipe)); it('sorts strings', () => { diff --git a/examples/TestProvider/test.spec.ts b/examples/TestProvider/test.spec.ts index 9f70b164df..156fff38cc 100644 --- a/examples/TestProvider/test.spec.ts +++ b/examples/TestProvider/test.spec.ts @@ -14,6 +14,7 @@ class TargetService { } describe('TestProvider', () => { + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(TargetService)); it('returns value on echo', () => { diff --git a/examples/TestProviderInComponent/test.spec.ts b/examples/TestProviderInComponent/test.spec.ts index a02acba55b..c7ed7cdd8c 100644 --- a/examples/TestProviderInComponent/test.spec.ts +++ b/examples/TestProviderInComponent/test.spec.ts @@ -22,6 +22,7 @@ describe('TestProviderInComponent', () => { // parameter of MockBuilder. // Because we do not care about TargetComponent, we pass it as // the second parameter for being replaced with a mock copy. + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(TargetService, TargetComponent)); it('has access to the service via a component', () => { diff --git a/examples/TestProviderInDirective/test.spec.ts b/examples/TestProviderInDirective/test.spec.ts index ce013e54a6..860ad5ed35 100644 --- a/examples/TestProviderInDirective/test.spec.ts +++ b/examples/TestProviderInDirective/test.spec.ts @@ -1,4 +1,11 @@ -import { Directive, ElementRef, Injectable, OnInit, TemplateRef, ViewContainerRef } from '@angular/core'; +import { + Directive, + ElementRef, + Injectable, + OnInit, + TemplateRef, + ViewContainerRef, +} from '@angular/core'; import { MockBuilder, MockRender, ngMocks } from 'ng-mocks'; // A simple service, might have contained more logic, @@ -37,6 +44,7 @@ describe('TestProviderInDirective', () => { // parameter of MockBuilder. // Because we do not care about TargetDirective, we pass it as // the second parameter for being replaced with a mock copy. + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(TargetService, TargetDirective)); it('has access to the service via a directive', () => { diff --git a/examples/TestProviderWithDependencies/test.spec.ts b/examples/TestProviderWithDependencies/test.spec.ts index 8b6894437e..92cd94736f 100644 --- a/examples/TestProviderWithDependencies/test.spec.ts +++ b/examples/TestProviderWithDependencies/test.spec.ts @@ -44,6 +44,7 @@ describe('TestProviderWithDependencies', () => { // Because we want to test the service, we pass it as the first // parameter of MockBuilder. To correctly satisfy its dependencies // we need to pass its module as the second parameter. + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(TargetService, TargetModule)); beforeAll(() => { diff --git a/examples/TestProviderWithUseClass/test.spec.ts b/examples/TestProviderWithUseClass/test.spec.ts index 437950f41a..edcd5565f7 100644 --- a/examples/TestProviderWithUseClass/test.spec.ts +++ b/examples/TestProviderWithUseClass/test.spec.ts @@ -51,6 +51,7 @@ describe('TestProviderWithUseClass', () => { // Because we want to test the service, we pass it as the first // parameter of MockBuilder. To correctly satisfy its dependencies // we need to pass its module as the second parameter. + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(Target1Service, TargetModule)); beforeAll(() => { diff --git a/examples/TestProviderWithUseExisting/test.spec.ts b/examples/TestProviderWithUseExisting/test.spec.ts index 40caa663cc..e29c2cdfbd 100644 --- a/examples/TestProviderWithUseExisting/test.spec.ts +++ b/examples/TestProviderWithUseExisting/test.spec.ts @@ -38,6 +38,7 @@ describe('TestProviderWithUseExisting', () => { // Because we want to test the service, we pass it as the first // parameter of MockBuilder. To correctly satisfy its initialization // we need to pass its module as the second parameter. + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(TargetService, TargetModule)); beforeAll(() => { diff --git a/examples/TestProviderWithUseFactory/test.spec.ts b/examples/TestProviderWithUseFactory/test.spec.ts index c184b6eccd..25546a2bc9 100644 --- a/examples/TestProviderWithUseFactory/test.spec.ts +++ b/examples/TestProviderWithUseFactory/test.spec.ts @@ -31,6 +31,7 @@ describe('TestProviderWithUseFactory', () => { // Because we want to test the service, we pass it as the first // parameter of MockBuilder. To correctly satisfy its initialization // we need to pass its module as the second parameter. + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(TargetService, TargetModule)); beforeAll(() => { diff --git a/examples/TestProviderWithUseValue/test.spec.ts b/examples/TestProviderWithUseValue/test.spec.ts index 56ce4da8ea..ea671e641b 100644 --- a/examples/TestProviderWithUseValue/test.spec.ts +++ b/examples/TestProviderWithUseValue/test.spec.ts @@ -27,6 +27,7 @@ describe('TestProviderWithUseValue', () => { // Because we want to test the service, we pass it as the first // parameter of MockBuilder. To correctly satisfy its initialization // we need to pass its module as the second parameter. + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(TargetService, TargetModule)); it('creates TargetService', () => { diff --git a/examples/TestRoute/test.spec.ts b/examples/TestRoute/test.spec.ts index f817b496c3..98d70a7152 100644 --- a/examples/TestRoute/test.spec.ts +++ b/examples/TestRoute/test.spec.ts @@ -58,7 +58,11 @@ class TargetRoutingModule {} class TargetModule {} describe('TestRoute:Route', () => { - beforeEach(() => MockBuilder(RouterModule, TargetModule).keep(RouterTestingModule.withRoutes([]))); + beforeEach(() => { + return MockBuilder(RouterModule, TargetModule).keep( + RouterTestingModule.withRoutes([]), + ); + }); it('renders /1 with Target1Component', fakeAsync(() => { const fixture = MockRender(RouterOutlet); @@ -74,7 +78,7 @@ describe('TestRoute:Route', () => { // We should see Target1Component component on /1 page. expect(location.path()).toEqual('/1'); - expect(() => ngMocks.find(fixture, Target1Component)).not.toThrow(); + expect(() => ngMocks.find(Target1Component)).not.toThrow(); })); it('renders /2 with Target2Component', fakeAsync(() => { @@ -91,7 +95,7 @@ describe('TestRoute:Route', () => { // We should see Target2Component component on /2 page. expect(location.path()).toEqual('/2'); - expect(() => ngMocks.find(fixture, Target2Component)).not.toThrow(); + expect(() => ngMocks.find(Target2Component)).not.toThrow(); })); }); @@ -105,9 +109,11 @@ describe('TestRoute:Component', () => { // RouterModule to have its routes, and to add // RouterTestingModule.withRoutes([]), yes yes, with empty routes // to have tools for testing. - beforeEach(() => - MockBuilder(TargetComponent, TargetModule).keep(RouterModule).keep(RouterTestingModule.withRoutes([])), - ); + beforeEach(() => { + return MockBuilder(TargetComponent, TargetModule) + .keep(RouterModule) + .keep(RouterTestingModule.withRoutes([])); + }); it('navigates between pages', fakeAsync(() => { const fixture = MockRender(TargetComponent); @@ -123,11 +129,11 @@ describe('TestRoute:Component', () => { // By default our routes do not have a component. // Therefore non of them should be rendered. expect(location.path()).toEqual('/'); - expect(() => ngMocks.find(fixture, Target1Component)).toThrow(); - expect(() => ngMocks.find(fixture, Target2Component)).toThrow(); + expect(() => ngMocks.find(Target1Component)).toThrow(); + expect(() => ngMocks.find(Target2Component)).toThrow(); // Let's extract our navigation links. - const links = ngMocks.findAll(fixture, 'a'); + const links = ngMocks.findAll('a'); // Checking where we land if we click the first link. if (fixture.ngZone) { @@ -143,7 +149,7 @@ describe('TestRoute:Component', () => { } // We should see Target1Component component on /1 page. expect(location.path()).toEqual('/1'); - expect(() => ngMocks.find(fixture, Target1Component)).not.toThrow(); + expect(() => ngMocks.find(Target1Component)).not.toThrow(); // Checking where we land if we click the second link. if (fixture.ngZone) { @@ -157,6 +163,6 @@ describe('TestRoute:Component', () => { } // We should see Target2Component component on /2 page. expect(location.path()).toEqual('/2'); - expect(() => ngMocks.find(fixture, Target2Component)).not.toThrow(); + expect(() => ngMocks.find(Target2Component)).not.toThrow(); })); }); diff --git a/examples/TestRoutingGuard/test.spec.ts b/examples/TestRoutingGuard/test.spec.ts index 1294cc92f7..e5b667534b 100644 --- a/examples/TestRoutingGuard/test.spec.ts +++ b/examples/TestRoutingGuard/test.spec.ts @@ -1,9 +1,24 @@ import { Location } from '@angular/common'; -import { Component, Injectable, NgModule, VERSION } from '@angular/core'; +import { + Component, + Injectable, + NgModule, + VERSION, +} from '@angular/core'; import { fakeAsync, TestBed, tick } from '@angular/core/testing'; -import { CanActivate, Router, RouterModule, RouterOutlet } from '@angular/router'; +import { + CanActivate, + Router, + RouterModule, + RouterOutlet, +} from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; -import { MockBuilder, MockRender, ngMocks, NG_MOCKS_GUARDS } from 'ng-mocks'; +import { + MockBuilder, + MockRender, + ngMocks, + NG_MOCKS_GUARDS, +} from 'ng-mocks'; import { from, Observable } from 'rxjs'; import { mapTo } from 'rxjs/operators'; @@ -17,7 +32,10 @@ class LoginService { // A guard we want to test. @Injectable() class LoginGuard implements CanActivate { - public constructor(protected router: Router, protected service: LoginService) {} + public constructor( + protected router: Router, + protected service: LoginService, + ) {} public canActivate(): boolean | Observable { if (this.service.isLoggedIn) { @@ -95,12 +113,12 @@ describe('TestRoutingGuard', () => { // RouterTestingModule.withRoutes([]), yes yes, with empty routes // to have tools for testing. And the last thing is to exclude // `NG_MOCKS_GUARDS` to remove all other guards. - beforeEach(() => - MockBuilder(LoginGuard, TargetModule) + beforeEach(() => { + return MockBuilder(LoginGuard, TargetModule) .exclude(NG_MOCKS_GUARDS) .keep(RouterModule) - .keep(RouterTestingModule.withRoutes([])), - ); + .keep(RouterTestingModule.withRoutes([])); + }); // It is important to run routing tests in fakeAsync. it('redirects to login', fakeAsync(() => { @@ -123,7 +141,7 @@ describe('TestRoutingGuard', () => { // Because by default we are not logged, the guard should // redirect us /login page. expect(location.path()).toEqual('/login'); - expect(() => ngMocks.find(fixture, LoginComponent)).not.toThrow(); + expect(() => ngMocks.find(LoginComponent)).not.toThrow(); })); it('loads dashboard', fakeAsync(() => { @@ -144,6 +162,6 @@ describe('TestRoutingGuard', () => { // Because now we are logged in, the guard should let us land on // the dashboard. expect(location.path()).toEqual('/'); - expect(() => ngMocks.find(fixture, DashboardComponent)).not.toThrow(); + expect(() => ngMocks.find(DashboardComponent)).not.toThrow(); })); }); diff --git a/examples/TestRoutingResolver/test.spec.ts b/examples/TestRoutingResolver/test.spec.ts index 6f824c3f4f..545f2b54de 100644 --- a/examples/TestRoutingResolver/test.spec.ts +++ b/examples/TestRoutingResolver/test.spec.ts @@ -1,7 +1,13 @@ import { Location } from '@angular/common'; import { Component, Injectable, NgModule } from '@angular/core'; import { fakeAsync, TestBed, tick } from '@angular/core/testing'; -import { ActivatedRoute, Resolve, Router, RouterModule, RouterOutlet } from '@angular/router'; +import { + ActivatedRoute, + Resolve, + Router, + RouterModule, + RouterOutlet, +} from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { MockBuilder, MockRender, ngMocks } from 'ng-mocks'; import { combineLatest, from, Observable, of } from 'rxjs'; @@ -23,7 +29,9 @@ class DataResolver implements Resolve<{ flag: boolean }> { public constructor(protected service: DataService) {} public resolve() { - return combineLatest([this.service.data()]).pipe(map(([flag]) => ({ flag }))); + return combineLatest([this.service.data()]).pipe( + map(([flag]) => ({ flag })), + ); } } @@ -74,7 +82,11 @@ describe('TestRoutingResolver', () => { // need to keep RouterModule to have its routes, and to // add RouterTestingModule.withRoutes([]), yes yes, with empty // routes to have tools for testing. - beforeEach(() => MockBuilder(DataResolver, TargetModule).keep(RouterModule).keep(RouterTestingModule.withRoutes([]))); + beforeEach(() => { + return MockBuilder(DataResolver, TargetModule) + .keep(RouterModule) + .keep(RouterTestingModule.withRoutes([])); + }); // It is important to run routing tests in fakeAsync. it('provides data to on the route', fakeAsync(() => { @@ -100,7 +112,7 @@ describe('TestRoutingResolver', () => { expect(location.path()).toEqual('/target'); // Let's extract ActivatedRoute of the current component. - const el = ngMocks.find(fixture, TargetComponent); + const el = ngMocks.find(TargetComponent); const route: ActivatedRoute = el.injector.get(ActivatedRoute); // Now we can assert that it has expected data. diff --git a/examples/TestStructuralDirective/test.spec.ts b/examples/TestStructuralDirective/test.spec.ts index 36790b22de..03b738e19c 100644 --- a/examples/TestStructuralDirective/test.spec.ts +++ b/examples/TestStructuralDirective/test.spec.ts @@ -1,4 +1,9 @@ -import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; +import { + Directive, + Input, + TemplateRef, + ViewContainerRef, +} from '@angular/core'; import { MockBuilder, MockRender } from 'ng-mocks'; // This directive is the same as `ngIf`, @@ -7,7 +12,10 @@ import { MockBuilder, MockRender } from 'ng-mocks'; selector: '[target]', }) class TargetDirective { - public constructor(protected templateRef: TemplateRef, protected viewContainerRef: ViewContainerRef) {} + public constructor( + protected templateRef: TemplateRef, + protected viewContainerRef: ViewContainerRef, + ) {} @Input() public set target(value: any) { if (value) { @@ -22,6 +30,7 @@ describe('TestStructuralDirective', () => { // Because we want to test the directive, we pass it as the first // parameter of MockBuilder. We can omit the second parameter, // because there are no dependencies. + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(TargetDirective)); it('hides and renders its content', () => { diff --git a/examples/TestStructuralDirectiveWithContext/test.spec.ts b/examples/TestStructuralDirectiveWithContext/test.spec.ts index 14df2fb14b..e259ca9a9f 100644 --- a/examples/TestStructuralDirectiveWithContext/test.spec.ts +++ b/examples/TestStructuralDirectiveWithContext/test.spec.ts @@ -1,4 +1,9 @@ -import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; +import { + Directive, + Input, + TemplateRef, + ViewContainerRef, +} from '@angular/core'; import { MockBuilder, MockRender } from 'ng-mocks'; export interface ITargetContext { @@ -34,6 +39,7 @@ describe('TestStructuralDirectiveWithContext', () => { // Because we want to test the directive, we pass it as the first // parameter of MockBuilder. We can omit the second parameter, // because there are no dependencies. + // Do not forget to return the promise of MockBuilder. beforeEach(() => MockBuilder(TargetDirective)); it('renders passed values', () => { @@ -41,7 +47,8 @@ describe('TestStructuralDirectiveWithContext', () => { `
    {{index}}: {{ value }} -
    `, +
    + `, { values: ['hello', 'world'], }, diff --git a/examples/TestToken/test.spec.ts b/examples/TestToken/test.spec.ts index f71246785b..6cc62a1921 100644 --- a/examples/TestToken/test.spec.ts +++ b/examples/TestToken/test.spec.ts @@ -47,9 +47,14 @@ describe('TestToken', () => { // the chain on MockBuilder. To correctly satisfy their // initialization we need to pass its module as the second // parameter. - beforeEach(() => - MockBuilder().mock(TargetModule).keep(TOKEN_CLASS).keep(TOKEN_EXISTING).keep(TOKEN_FACTORY).keep(TOKEN_VALUE), - ); + beforeEach(() => { + return MockBuilder() + .mock(TargetModule) + .keep(TOKEN_CLASS) + .keep(TOKEN_EXISTING) + .keep(TOKEN_FACTORY) + .keep(TOKEN_VALUE); + }); it('creates TOKEN_CLASS', () => { const token = TestBed.get(TOKEN_CLASS); diff --git a/examples/ngMocksFaster/test.spec.ts b/examples/ngMocksFaster/test.spec.ts index fe957a0325..7a15821ac8 100644 --- a/examples/ngMocksFaster/test.spec.ts +++ b/examples/ngMocksFaster/test.spec.ts @@ -1,7 +1,13 @@ // tslint:disable strict-type-predicates import { Component, Injectable } from '@angular/core'; -import { MockBuilder, MockInstance, MockRender, MockReset, ngMocks } from 'ng-mocks'; +import { + MockBuilder, + MockInstance, + MockRender, + MockReset, + ngMocks, +} from 'ng-mocks'; @Injectable() class TargetService { @@ -27,14 +33,18 @@ describe('examples:performance', () => { // A normal setup of the TestBed, TargetService will be replaced // with its mock copy. - beforeEach(() => MockBuilder(TargetComponent).mock(TargetService)); + beforeEach(() => { + return MockBuilder(TargetComponent).mock(TargetService); + }); // Configuring behavior of the mock TargetService. beforeAll(() => { MockInstance(TargetService, { init: instance => { instance.method = - typeof jest === 'undefined' ? jasmine.createSpy().and.returnValue(5) : jest.fn().mockReturnValue(5); + typeof jest === 'undefined' + ? jasmine.createSpy().and.returnValue(5) + : jest.fn().mockReturnValue(5); // in case of jest // instance.method = jest.fn().mockReturnValue(5); instance.prop = 123; @@ -51,7 +61,9 @@ describe('examples:performance', () => { expect(fixture.point.componentInstance.service.prop).toBe(123); const actual = fixture.point.componentInstance.service.method(); expect(actual).toBe(5); - expect(fixture.point.componentInstance.service.method).toHaveBeenCalledTimes(1); + expect( + fixture.point.componentInstance.service.method, + ).toHaveBeenCalledTimes(1); }); it('test:2', () => { @@ -60,7 +72,9 @@ describe('examples:performance', () => { expect(fixture.point.componentInstance.service.prop).toBe(123); const actual = fixture.point.componentInstance.service.method(); expect(actual).toBe(5); - expect(fixture.point.componentInstance.service.method).toHaveBeenCalledTimes(1); + expect( + fixture.point.componentInstance.service.method, + ).toHaveBeenCalledTimes(1); }); }); @@ -71,7 +85,12 @@ describe('examples:performance', () => { // allows its pointer being the same between tests // and this let ngMocks.faster do its job. const mock = { - method: typeof jest === 'undefined' ? jasmine.createSpy().and.returnValue(5) : jest.fn().mockReturnValue(5), + method: + typeof jest === 'undefined' + ? jasmine.createSpy().and.returnValue(5) + : jest.fn().mockReturnValue(5), + // in case of jest + // instance.method = jest.fn().mockReturnValue(5); prop: 123, }; @@ -87,7 +106,9 @@ describe('examples:performance', () => { // A normal setup of the TestBed, TargetService will be replaced // with its mock copy. - beforeEach(() => MockBuilder(TargetComponent).mock(TargetService, mock)); + beforeEach(() => { + return MockBuilder(TargetComponent).mock(TargetService, mock); + }); it('test:1', () => { const fixture = MockRender(TargetComponent); @@ -95,7 +116,9 @@ describe('examples:performance', () => { expect(fixture.point.componentInstance.service.prop).toBe(123); const actual = fixture.point.componentInstance.service.method(); expect(actual).toBe(5); - expect(fixture.point.componentInstance.service.method).toHaveBeenCalledTimes(1); + expect( + fixture.point.componentInstance.service.method, + ).toHaveBeenCalledTimes(1); }); it('test:2', () => { @@ -104,7 +127,9 @@ describe('examples:performance', () => { expect(fixture.point.componentInstance.service.prop).toBe(123); const actual = fixture.point.componentInstance.service.method(); expect(actual).toBe(5); - expect(fixture.point.componentInstance.service.method).toHaveBeenCalledTimes(1); + expect( + fixture.point.componentInstance.service.method, + ).toHaveBeenCalledTimes(1); }); }); }); diff --git a/examples/ngMocksGuts/test.spec.ts b/examples/ngMocksGuts/test.spec.ts index 02b21c955e..66b8147bbe 100644 --- a/examples/ngMocksGuts/test.spec.ts +++ b/examples/ngMocksGuts/test.spec.ts @@ -15,7 +15,13 @@ import { PipeTransform, } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { MockDirective, MockModule, MockPipe, MockService, ngMocks } from 'ng-mocks'; +import { + MockDirective, + MockModule, + MockPipe, + MockService, + ngMocks, +} from 'ng-mocks'; const TARGET1 = new InjectionToken('TARGET1'); @@ -47,21 +53,26 @@ class Target2Component {} @Component({ selector: 'target1', template: `
    - {{ greeting }} {{ greeting | target1 }} {{ target }} + {{ greeting }} {{ greeting | target1 }} + {{ target }}
    `, }) class Target1Component { @Input() public greeting: string | null = null; - @Output() public readonly update: EventEmitter = new EventEmitter(); + @Output() + public readonly update: EventEmitter = new EventEmitter(); - public constructor(@Inject(TARGET1) public readonly target: string) {} + public constructor( + @Inject(TARGET1) public readonly target: string, + ) {} } @Directive({ selector: '[target1]', }) class Target1Directive implements OnDestroy { - @Output() public readonly target1: EventEmitter = new EventEmitter(); + @Output() + public readonly target1: EventEmitter = new EventEmitter(); public constructor(public readonly service: Target1Service) { this.service.callback = () => { @@ -121,7 +132,9 @@ describe('ngMocks.guts:NO_ERRORS_SCHEMA', () => { it('creates component', () => { expect(component).toEqual(jasmine.any(Target1Component)); - expect(fixture.nativeElement.innerHTML).toContain(''); + expect(fixture.nativeElement.innerHTML).toContain( + '', + ); expect(fixture.nativeElement.innerHTML).not.toContain('hello'); component.greeting = 'hello'; fixture.detectChanges(); @@ -135,7 +148,11 @@ describe('ngMocks.guts:legacy', () => { beforeEach(() => { TestBed.configureTestingModule({ - declarations: [MockPipe(Target1Pipe), MockDirective(Target1Directive), Target1Component], + declarations: [ + MockPipe(Target1Pipe), + MockDirective(Target1Directive), + Target1Component, + ], imports: [CommonModule, MockModule(Target2Module)], providers: [ { @@ -154,7 +171,9 @@ describe('ngMocks.guts:legacy', () => { it('creates component', () => { expect(component).toEqual(jasmine.any(Target1Component)); - expect(fixture.nativeElement.innerHTML).toContain(''); + expect(fixture.nativeElement.innerHTML).toContain( + '', + ); expect(fixture.nativeElement.innerHTML).not.toContain('hello'); component.greeting = 'hello'; fixture.detectChanges(); @@ -167,14 +186,18 @@ describe('ngMocks.guts:normal', () => { let component: Target1Component; beforeEach(() => { - TestBed.configureTestingModule(ngMocks.guts(Target1Component, Target1Module)); + TestBed.configureTestingModule( + ngMocks.guts(Target1Component, Target1Module), + ); fixture = TestBed.createComponent(Target1Component); component = fixture.componentInstance; }); it('creates component', () => { expect(component).toEqual(jasmine.any(Target1Component)); - expect(fixture.nativeElement.innerHTML).toContain(''); + expect(fixture.nativeElement.innerHTML).toContain( + '', + ); expect(fixture.nativeElement.innerHTML).not.toContain('hello'); component.greeting = 'hello'; fixture.detectChanges(); diff --git a/lib/common/jit-reflector.spec.ts b/lib/common/jit-reflector.spec.ts index a30067d82a..aae792ae96 100644 --- a/lib/common/jit-reflector.spec.ts +++ b/lib/common/jit-reflector.spec.ts @@ -47,9 +47,15 @@ describe('JitReflector', () => { const expectedLcProperty = 'string'; instance.mock.hasLifecycleHook.and.returnValue(false); - const actual = instance.hasLifecycleHook(expectedType, expectedLcProperty); - - expect(instance.mock.hasLifecycleHook).toHaveBeenCalledWith(expectedType, expectedLcProperty); + const actual = instance.hasLifecycleHook( + expectedType, + expectedLcProperty, + ); + + expect(instance.mock.hasLifecycleHook).toHaveBeenCalledWith( + expectedType, + expectedLcProperty, + ); expect(actual).toEqual(false); }); @@ -83,7 +89,9 @@ describe('JitReflector', () => { }); it('shallowAnnotations', () => { - expect(() => instance.shallowAnnotations()).toThrowError(/Not supported in JIT mode/); + expect(() => instance.shallowAnnotations()).toThrowError( + /Not supported in JIT mode/, + ); }); it('tryAnnotations', () => { diff --git a/lib/common/mock.spec.ts b/lib/common/mock.spec.ts index ff31fb0959..8f6d70c222 100644 --- a/lib/common/mock.spec.ts +++ b/lib/common/mock.spec.ts @@ -1,6 +1,12 @@ // tslint:disable max-file-line-count -import { Component, Directive, NgModule, Pipe, PipeTransform } from '@angular/core'; +import { + Component, + Directive, + NgModule, + Pipe, + PipeTransform, +} from '@angular/core'; import { ControlValueAccessor } from '@angular/forms'; import { MockComponent } from '../mock-component/mock-component'; @@ -43,7 +49,9 @@ class ChildModuleClass extends ParentClass implements PipeTransform { @Component({ template: '', }) -class ChildComponentClass extends ParentClass implements PipeTransform, ControlValueAccessor { +class ChildComponentClass + extends ParentClass + implements PipeTransform, ControlValueAccessor { protected childValue = true; public childMethod(): boolean { @@ -66,7 +74,9 @@ class ChildComponentClass extends ParentClass implements PipeTransform, ControlV @Directive({ selector: 'mock', }) -class ChildDirectiveClass extends ParentClass implements PipeTransform, ControlValueAccessor { +class ChildDirectiveClass + extends ParentClass + implements PipeTransform, ControlValueAccessor { protected childValue = true; public childMethod(): boolean { @@ -106,16 +116,24 @@ describe('Mock', () => { const instance = new (MockModule(ChildModuleClass))(); expect(instance).toEqual(jasmine.any(ChildModuleClass)); expect((instance as any).__ngMocksMock).toEqual(true); - expect((instance as any).__ngMocksMockControlValueAccessor).toEqual(undefined); - expect(instance.parentMethod()).toBeUndefined('mock to an empty function'); - expect(instance.childMethod()).toBeUndefined('mock to an empty function'); + expect( + (instance as any).__ngMocksMockControlValueAccessor, + ).toEqual(undefined); + expect(instance.parentMethod()).toBeUndefined( + 'mock to an empty function', + ); + expect(instance.childMethod()).toBeUndefined( + 'mock to an empty function', + ); }); it('should affect as MockComponent', () => { const instance = new (MockComponent(ChildComponentClass))(); expect(instance).toEqual(jasmine.any(ChildComponentClass)); expect((instance as any).__ngMocksMock).toEqual(true); - expect((instance as any).__ngMocksMockControlValueAccessor).toEqual(true); + expect( + (instance as any).__ngMocksMockControlValueAccessor, + ).toEqual(true); const spy = jasmine.createSpy('spy'); instance.registerOnChange(spy); @@ -130,7 +148,9 @@ describe('Mock', () => { const instance = new (MockDirective(ChildDirectiveClass))(); expect(instance).toEqual(jasmine.any(ChildDirectiveClass)); expect((instance as any).__ngMocksMock).toEqual(true); - expect((instance as any).__ngMocksMockControlValueAccessor).toEqual(true); + expect( + (instance as any).__ngMocksMockControlValueAccessor, + ).toEqual(true); const spy = jasmine.createSpy('spy'); instance.registerOnChange(spy); @@ -145,7 +165,9 @@ describe('Mock', () => { const instance = new (MockPipe(ChildPipeClass))(); expect(instance).toEqual(jasmine.any(ChildPipeClass)); expect((instance as any).__ngMocksMock).toEqual(true); - expect((instance as any).__ngMocksMockControlValueAccessor).toEqual(undefined); + expect( + (instance as any).__ngMocksMockControlValueAccessor, + ).toEqual(undefined); expect(instance.parentMethod()).toBeUndefined(); expect(instance.childMethod()).toBeUndefined(); }); @@ -241,7 +263,9 @@ describe('definitions', () => { class TestComponent extends TestMock {} const instance: any = new TestComponent(); - expect(Object.getOwnPropertyDescriptor(instance, 'test')).toBeDefined(); + expect( + Object.getOwnPropertyDescriptor(instance, 'test'), + ).toBeDefined(); }); it('skips existing properties from mockOf', () => { diff --git a/lib/mock-builder/mock-builder.performance.spec.ts b/lib/mock-builder/mock-builder.performance.spec.ts index 0e067f426a..bafb4b7a9c 100644 --- a/lib/mock-builder/mock-builder.performance.spec.ts +++ b/lib/mock-builder/mock-builder.performance.spec.ts @@ -1,6 +1,12 @@ // tslint:disable max-file-line-count -import { Component, Directive, Injectable, InjectionToken, NgModule } from '@angular/core'; +import { + Component, + Directive, + Injectable, + InjectionToken, + NgModule, +} from '@angular/core'; import { ngMocks } from '../mock-helper/mock-helper'; @@ -55,8 +61,14 @@ describe('MockBuilderPerformance', () => { it('accepts the same beforeCC', () => { const beforeCC = () => undefined; - const ngModule1 = MockBuilder().mock(Target1Module).beforeCompileComponents(beforeCC).build(); - const ngModule2 = MockBuilder().mock(Target1Module).beforeCompileComponents(beforeCC).build(); + const ngModule1 = MockBuilder() + .mock(Target1Module) + .beforeCompileComponents(beforeCC) + .build(); + const ngModule2 = MockBuilder() + .mock(Target1Module) + .beforeCompileComponents(beforeCC) + .build(); expect(ngModule1.imports?.[0]).toBe(ngModule2.imports?.[0]); }); @@ -64,7 +76,10 @@ describe('MockBuilderPerformance', () => { const beforeCC = () => undefined; const ngModule1 = MockBuilder().mock(Target1Module).build(); - const ngModule2 = MockBuilder().mock(Target1Module).beforeCompileComponents(beforeCC).build(); + const ngModule2 = MockBuilder() + .mock(Target1Module) + .beforeCompileComponents(beforeCC) + .build(); expect(ngModule1.imports?.[0]).not.toBe(ngModule2.imports?.[0]); }); @@ -72,8 +87,14 @@ describe('MockBuilderPerformance', () => { const beforeCC1 = () => undefined; const beforeCC2 = () => undefined; - const ngModule1 = MockBuilder().mock(Target1Module).beforeCompileComponents(beforeCC1).build(); - const ngModule2 = MockBuilder().mock(Target1Module).beforeCompileComponents(beforeCC2).build(); + const ngModule1 = MockBuilder() + .mock(Target1Module) + .beforeCompileComponents(beforeCC1) + .build(); + const ngModule2 = MockBuilder() + .mock(Target1Module) + .beforeCompileComponents(beforeCC2) + .build(); expect(ngModule1.imports?.[0]).not.toBe(ngModule2.imports?.[0]); }); @@ -98,46 +119,82 @@ describe('MockBuilderPerformance', () => { }); it('accepts the same replaceDef', () => { - const ngModule1 = MockBuilder().keep(Target1Module).replace(Target1Component, Target2Component).build(); - const ngModule2 = MockBuilder().keep(Target1Module).replace(Target1Component, Target2Component).build(); + const ngModule1 = MockBuilder() + .keep(Target1Module) + .replace(Target1Component, Target2Component) + .build(); + const ngModule2 = MockBuilder() + .keep(Target1Module) + .replace(Target1Component, Target2Component) + .build(); expect(ngModule1.imports?.[0]).toBe(ngModule2.imports?.[0]); }); it('fails on a different size replaceDef', () => { const ngModule1 = MockBuilder().keep(Target1Module).build(); - const ngModule2 = MockBuilder().keep(Target1Module).replace(Target1Component, Target2Component).build(); + const ngModule2 = MockBuilder() + .keep(Target1Module) + .replace(Target1Component, Target2Component) + .build(); expect(ngModule1.imports?.[0]).not.toBe(ngModule2.imports?.[0]); }); it('fails on a missed replaceDef', () => { - const ngModule1 = MockBuilder().keep(Target1Module).replace(Target1Component, Target2Component).build(); - const ngModule2 = MockBuilder().keep(Target1Module).replace(Target1Directive, Target2Directive).build(); + const ngModule1 = MockBuilder() + .keep(Target1Module) + .replace(Target1Component, Target2Component) + .build(); + const ngModule2 = MockBuilder() + .keep(Target1Module) + .replace(Target1Directive, Target2Directive) + .build(); expect(ngModule1.imports?.[0]).not.toBe(ngModule2.imports?.[0]); }); it('accepts the same excludeDef', () => { - const ngModule1 = MockBuilder().keep(Target1Module).exclude(Target1Component).build(); - const ngModule2 = MockBuilder().keep(Target1Module).exclude(Target1Component).build(); + const ngModule1 = MockBuilder() + .keep(Target1Module) + .exclude(Target1Component) + .build(); + const ngModule2 = MockBuilder() + .keep(Target1Module) + .exclude(Target1Component) + .build(); expect(ngModule1.imports?.[0]).toBe(ngModule2.imports?.[0]); }); it('fails on a different size excludeDef', () => { const ngModule1 = MockBuilder().keep(Target1Module).build(); - const ngModule2 = MockBuilder().keep(Target1Module).exclude(Target1Component).build(); + const ngModule2 = MockBuilder() + .keep(Target1Module) + .exclude(Target1Component) + .build(); expect(ngModule1.imports?.[0]).not.toBe(ngModule2.imports?.[0]); }); it('fails on a missed excludeDef', () => { - const ngModule1 = MockBuilder().keep(Target1Module).exclude(Target1Component).build(); - const ngModule2 = MockBuilder().keep(Target1Module).exclude(Target2Component).build(); + const ngModule1 = MockBuilder() + .keep(Target1Module) + .exclude(Target1Component) + .build(); + const ngModule2 = MockBuilder() + .keep(Target1Module) + .exclude(Target2Component) + .build(); expect(ngModule1.imports?.[0]).not.toBe(ngModule2.imports?.[0]); }); it('accepts the same mockDef', () => { - const ngModule1 = MockBuilder().mock(Target1Module).mock(Target1Component).build(); - const ngModule2 = MockBuilder().mock(Target1Module).mock(Target1Component).build(); + const ngModule1 = MockBuilder() + .mock(Target1Module) + .mock(Target1Component) + .build(); + const ngModule2 = MockBuilder() + .mock(Target1Module) + .mock(Target1Component) + .build(); expect(ngModule1.imports?.[0]).toBe(ngModule2.imports?.[0]); }); @@ -164,42 +221,70 @@ describe('MockBuilderPerformance', () => { const ngModule1 = MockBuilder().build(); const ngModule2 = MockBuilder().provide(Target1Service).build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('fails on a missed providerDef', () => { const ngModule1 = MockBuilder().provide(Target1Service).build(); const ngModule2 = MockBuilder().provide(Target2Service).build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('accepts on the same providerDef useValue', () => { - const ngModule1 = MockBuilder().provide({ provide: Target1Service, useValue: 1 }).build(); - const ngModule2 = MockBuilder().provide({ provide: Target1Service, useValue: 1 }).build(); + const ngModule1 = MockBuilder() + .provide({ provide: Target1Service, useValue: 1 }) + .build(); + const ngModule2 = MockBuilder() + .provide({ provide: Target1Service, useValue: 1 }) + .build(); expect(ngModule1.providers?.[0]).toBe(ngModule2.providers?.[0]); }); it('fails on a different providerDef useValue', () => { - const ngModule1 = MockBuilder().provide({ provide: Target1Service, useValue: 1 }).build(); - const ngModule2 = MockBuilder().provide({ provide: Target1Service, useValue: 2 }).build(); + const ngModule1 = MockBuilder() + .provide({ provide: Target1Service, useValue: 1 }) + .build(); + const ngModule2 = MockBuilder() + .provide({ provide: Target1Service, useValue: 2 }) + .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('accepts the same providerDef useValue', () => { - const ngModule1 = MockBuilder().provide({ provide: Target1Service, useClass: Target2Service }).build(); - const ngModule2 = MockBuilder().provide({ provide: Target1Service, useClass: Target2Service }).build(); + const ngModule1 = MockBuilder() + .provide({ provide: Target1Service, useClass: Target2Service }) + .build(); + const ngModule2 = MockBuilder() + .provide({ provide: Target1Service, useClass: Target2Service }) + .build(); expect(ngModule1.providers?.[0]).toBe(ngModule2.providers?.[0]); }); it('fails on a different providerDef useValue', () => { - const ngModule1 = MockBuilder().provide({ provide: Target1Service, useClass: Target1Service }).build(); - const ngModule2 = MockBuilder().provide({ provide: Target1Service, useClass: Target2Service }).build(); + const ngModule1 = MockBuilder() + .provide({ provide: Target1Service, useClass: Target1Service }) + .build(); + const ngModule2 = MockBuilder() + .provide({ provide: Target1Service, useClass: Target2Service }) + .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('accepts the same providerDef helperUseFactory', () => { const factory = () => 1; - const ngModule1 = MockBuilder().provide({ provide: Target1Service, useFactory: factory }).build(); - const ngModule2 = MockBuilder().provide({ provide: Target1Service, useFactory: factory }).build(); + const ngModule1 = MockBuilder() + .provide({ provide: Target1Service, useFactory: factory }) + .build(); + const ngModule2 = MockBuilder() + .provide({ provide: Target1Service, useFactory: factory }) + .build(); expect(ngModule1.providers?.[0]).toBe(ngModule2.providers?.[0]); }); @@ -211,19 +296,43 @@ describe('MockBuilderPerformance', () => { .provide({ provide: Target1Service, useFactory: () => 2 }) .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('accepts the same providerDef useExisting', () => { - const ngModule1 = MockBuilder().provide({ provide: Target1Service, useExisting: Target2Service }).build(); - const ngModule2 = MockBuilder().provide({ provide: Target1Service, useExisting: Target2Service }).build(); + const ngModule1 = MockBuilder() + .provide({ + provide: Target1Service, + useExisting: Target2Service, + }) + .build(); + const ngModule2 = MockBuilder() + .provide({ + provide: Target1Service, + useExisting: Target2Service, + }) + .build(); expect(ngModule1.providers?.[0]).toBe(ngModule2.providers?.[0]); }); it('fails on a different providerDef useExisting', () => { - const ngModule1 = MockBuilder().provide({ provide: Target1Service, useExisting: Target1Service }).build(); - const ngModule2 = MockBuilder().provide({ provide: Target1Service, useExisting: Target2Service }).build(); + const ngModule1 = MockBuilder() + .provide({ + provide: Target1Service, + useExisting: Target1Service, + }) + .build(); + const ngModule2 = MockBuilder() + .provide({ + provide: Target1Service, + useExisting: Target2Service, + }) + .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('accepts the same providerDef', () => { const def = { provide: Target1Service }; @@ -233,37 +342,63 @@ describe('MockBuilderPerformance', () => { expect(ngModule1.providers?.[0]).toBe(ngModule2.providers?.[0]); }); it('fails on a different providerDef', () => { - const ngModule1 = MockBuilder().provide({ provide: Target1Service }).build(); - const ngModule2 = MockBuilder().provide({ provide: Target1Service }).build(); + const ngModule1 = MockBuilder() + .provide({ provide: Target1Service }) + .build(); + const ngModule2 = MockBuilder() + .provide({ provide: Target1Service }) + .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('fails on a different multi flags', () => { - const ngModule1 = MockBuilder().provide({ provide: Target1Service, useValue: 1 }).build(); - const ngModule2 = MockBuilder().provide({ provide: Target1Service, useValue: 1, multi: true }).build(); + const ngModule1 = MockBuilder() + .provide({ provide: Target1Service, useValue: 1 }) + .build(); + const ngModule2 = MockBuilder() + .provide({ provide: Target1Service, useValue: 1, multi: true }) + .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('accepts the same multi flags', () => { - const ngModule1 = MockBuilder().provide({ provide: Target1Service, useValue: 1, multi: true }).build(); - const ngModule2 = MockBuilder().provide({ provide: Target1Service, useValue: 1, multi: true }).build(); + const ngModule1 = MockBuilder() + .provide({ provide: Target1Service, useValue: 1, multi: true }) + .build(); + const ngModule2 = MockBuilder() + .provide({ provide: Target1Service, useValue: 1, multi: true }) + .build(); expect(ngModule1.providers?.[0]).toBe(ngModule2.providers?.[0]); }); it('fails on a different multi size', () => { - const ngModule1 = MockBuilder().provide({ provide: Target1Service, useValue: 1, multi: true }).build(); + const ngModule1 = MockBuilder() + .provide({ provide: Target1Service, useValue: 1, multi: true }) + .build(); const ngModule2 = MockBuilder() .provide({ provide: Target1Service, useValue: 1, multi: true }) .provide({ provide: Target1Service, useValue: 2, multi: true }) .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('fails on a different multi values', () => { - const ngModule1 = MockBuilder().provide({ provide: Target1Service, useValue: 1, multi: true }).build(); - const ngModule2 = MockBuilder().provide({ provide: Target1Service, useValue: 2, multi: true }).build(); + const ngModule1 = MockBuilder() + .provide({ provide: Target1Service, useValue: 1, multi: true }) + .build(); + const ngModule2 = MockBuilder() + .provide({ provide: Target1Service, useValue: 2, multi: true }) + .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('accepts the same defProviders', () => { @@ -391,28 +526,60 @@ describe('MockBuilderPerformance', () => { }); it('accepts the same defValue', () => { - const ngModule1 = MockBuilder().mock(Target1Module).mock(Target1Service, 1).build(); - const ngModule2 = MockBuilder().mock(Target1Module).mock(Target1Service, 1).build(); + const ngModule1 = MockBuilder() + .mock(Target1Module) + .mock(Target1Service, 1) + .build(); + const ngModule2 = MockBuilder() + .mock(Target1Module) + .mock(Target1Service, 1) + .build(); expect(ngModule1.providers?.[0]).toBe(ngModule2.providers?.[0]); }); it('fails on a different size defValue', () => { - const ngModule1 = MockBuilder().mock(Target1Module).mock(Target1Service).build(); - const ngModule2 = MockBuilder().mock(Target1Module).mock(Target1Service, 1).build(); + const ngModule1 = MockBuilder() + .mock(Target1Module) + .mock(Target1Service) + .build(); + const ngModule2 = MockBuilder() + .mock(Target1Module) + .mock(Target1Service, 1) + .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('fails on a missed defValue', () => { - const ngModule1 = MockBuilder().mock(Target1Module).mock(Target1Service).mock(Target2Service, 2).build(); - const ngModule2 = MockBuilder().mock(Target1Module).mock(Target2Service).mock(Target1Service, 1).build(); + const ngModule1 = MockBuilder() + .mock(Target1Module) + .mock(Target1Service) + .mock(Target2Service, 2) + .build(); + const ngModule2 = MockBuilder() + .mock(Target1Module) + .mock(Target2Service) + .mock(Target1Service, 1) + .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('fails on a different defValue', () => { - const ngModule1 = MockBuilder().mock(Target1Module).mock(Target1Service, 1).build(); - const ngModule2 = MockBuilder().mock(Target1Module).mock(Target1Service, 2).build(); + const ngModule1 = MockBuilder() + .mock(Target1Module) + .mock(Target1Service, 1) + .build(); + const ngModule2 = MockBuilder() + .mock(Target1Module) + .mock(Target1Service, 2) + .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('accepts the same size configDef', () => { @@ -425,54 +592,98 @@ describe('MockBuilderPerformance', () => { const ngModule1 = MockBuilder().keep(Target1Module).build(); const ngModule2 = MockBuilder().keep(Target1Module, {}).build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('fails on a missed configDef', () => { - const ngModule1 = MockBuilder().keep(Target1Module).keep(Target2Module, {}).build(); - const ngModule2 = MockBuilder().keep(Target2Module).keep(Target1Module, {}).build(); + const ngModule1 = MockBuilder() + .keep(Target1Module) + .keep(Target2Module, {}) + .build(); + const ngModule2 = MockBuilder() + .keep(Target2Module) + .keep(Target1Module, {}) + .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('accepts the same configDef', () => { const config = {}; - const ngModule1 = MockBuilder().keep(Target1Module, config).build(); - const ngModule2 = MockBuilder().keep(Target1Module, config).build(); + const ngModule1 = MockBuilder() + .keep(Target1Module, config) + .build(); + const ngModule2 = MockBuilder() + .keep(Target1Module, config) + .build(); expect(ngModule1.providers?.[0]).toBe(ngModule2.providers?.[0]); }); it('fails on different dependency configDef', () => { - const ngModule1 = MockBuilder().keep(Target1Module, { dependency: true }).build(); - const ngModule2 = MockBuilder().keep(Target1Module, { dependency: false }).build(); + const ngModule1 = MockBuilder() + .keep(Target1Module, { dependency: true }) + .build(); + const ngModule2 = MockBuilder() + .keep(Target1Module, { dependency: false }) + .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('fails on different export configDef', () => { - const ngModule1 = MockBuilder().keep(Target1Module, { export: true }).build(); - const ngModule2 = MockBuilder().keep(Target1Module, { export: false }).build(); + const ngModule1 = MockBuilder() + .keep(Target1Module, { export: true }) + .build(); + const ngModule2 = MockBuilder() + .keep(Target1Module, { export: false }) + .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('fails on different exportAll configDef', () => { - const ngModule1 = MockBuilder().keep(Target1Module, { exportAll: true }).build(); - const ngModule2 = MockBuilder().keep(Target1Module, { exportAll: false }).build(); + const ngModule1 = MockBuilder() + .keep(Target1Module, { exportAll: true }) + .build(); + const ngModule2 = MockBuilder() + .keep(Target1Module, { exportAll: false }) + .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('accepts the same render configDef', () => { const render = {}; - const ngModule1 = MockBuilder().keep(Target1Module, { render }).build(); - const ngModule2 = MockBuilder().keep(Target1Module, { render }).build(); + const ngModule1 = MockBuilder() + .keep(Target1Module, { render }) + .build(); + const ngModule2 = MockBuilder() + .keep(Target1Module, { render }) + .build(); expect(ngModule1.providers?.[0]).toBe(ngModule2.providers?.[0]); }); it('fails on different render flag configDef', () => { - const ngModule1 = MockBuilder().keep(Target1Module, { render: true }).build(); - const ngModule2 = MockBuilder().keep(Target1Module, { render: false }).build(); + const ngModule1 = MockBuilder() + .keep(Target1Module, { render: true }) + .build(); + const ngModule2 = MockBuilder() + .keep(Target1Module, { render: false }) + .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('fails on different render length configDef', () => { - const ngModule1 = MockBuilder().keep(Target1Module, { render: {} }).build(); + const ngModule1 = MockBuilder() + .keep(Target1Module, { render: {} }) + .build(); const ngModule2 = MockBuilder() .keep(Target1Module, { render: { @@ -481,7 +692,9 @@ describe('MockBuilderPerformance', () => { }) .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('fails on different render.$implicit configDef', () => { const ngModule1 = MockBuilder() @@ -499,7 +712,9 @@ describe('MockBuilderPerformance', () => { }) .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('accepts the same render.variables configDef', () => { const variables = {}; @@ -543,7 +758,9 @@ describe('MockBuilderPerformance', () => { expect(ngModule1.providers?.[0]).toBe(ngModule2.providers?.[0]); }); it('fails on missed definition configDef', () => { - const ngModule1 = MockBuilder().keep(Target1Module, { render: {} }).build(); + const ngModule1 = MockBuilder() + .keep(Target1Module, { render: {} }) + .build(); const ngModule2 = MockBuilder() .keep(Target1Module, { render: { @@ -553,10 +770,16 @@ describe('MockBuilderPerformance', () => { }, }) .build(); - const ngModule3 = MockBuilder().keep(Target1Module, { render: {} }).build(); + const ngModule3 = MockBuilder() + .keep(Target1Module, { render: {} }) + .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); - expect(ngModule2.providers?.[0]).not.toBe(ngModule3.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); + expect(ngModule2.providers?.[0]).not.toBe( + ngModule3.providers?.[0], + ); }); it('fails on different render.variables configDef', () => { const ngModule1 = MockBuilder() @@ -579,7 +802,9 @@ describe('MockBuilderPerformance', () => { }) .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('fails on different values in render.variables configDef', () => { const ngModule1 = MockBuilder() @@ -601,7 +826,9 @@ describe('MockBuilderPerformance', () => { }) .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('fails on different amount of blocks in render configDef', () => { const ngModule1 = MockBuilder() @@ -620,7 +847,9 @@ describe('MockBuilderPerformance', () => { }) .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); it('fails on different block definitions in render configDef', () => { const ngModule1 = MockBuilder() @@ -642,6 +871,8 @@ describe('MockBuilderPerformance', () => { }) .build(); - expect(ngModule1.providers?.[0]).not.toBe(ngModule2.providers?.[0]); + expect(ngModule1.providers?.[0]).not.toBe( + ngModule2.providers?.[0], + ); }); }); diff --git a/lib/mock-builder/mock-builder.promise.spec.ts b/lib/mock-builder/mock-builder.promise.spec.ts index 78c9d22436..7eebd2c1e6 100644 --- a/lib/mock-builder/mock-builder.promise.spec.ts +++ b/lib/mock-builder/mock-builder.promise.spec.ts @@ -1,6 +1,14 @@ // tslint:disable no-console -import { Component, Directive, Injectable, InjectionToken, NgModule, Pipe, PipeTransform } from '@angular/core'; +import { + Component, + Directive, + Injectable, + InjectionToken, + NgModule, + Pipe, + PipeTransform, +} from '@angular/core'; import { getTestBedInjection } from '../common/core.helpers'; @@ -67,7 +75,9 @@ describe('MockBuilderPromise', () => { }); it('skips dependencies in mock providers', async () => { - await MockBuilder().mock(TargetService, TargetService, { dependency: true }); + await MockBuilder().mock(TargetService, TargetService, { + dependency: true, + }); expect(getTestBedInjection(TargetService)).toBeFalsy(); }); @@ -127,7 +137,11 @@ describe('MockBuilderPromise', () => { }); it('throws an error on a services replacement', () => { - expect(() => MockBuilder().replace(TargetModule, TargetService)).toThrowError(/Cannot replace the declaration/); - expect(() => MockBuilder().replace(TargetService, TargetModule)).toThrowError(/Cannot replace the declaration/); + expect(() => + MockBuilder().replace(TargetModule, TargetService), + ).toThrowError(/Cannot replace the declaration/); + expect(() => + MockBuilder().replace(TargetService, TargetModule), + ).toThrowError(/Cannot replace the declaration/); }); }); diff --git a/lib/mock-builder/promise/types.ts b/lib/mock-builder/promise/types.ts index c38d99c406..32776a3e3c 100644 --- a/lib/mock-builder/promise/types.ts +++ b/lib/mock-builder/promise/types.ts @@ -1,5 +1,7 @@ import { InjectionToken, Provider } from '@angular/core'; -import { NgModuleWithProviders, Type } from 'ng-mocks'; + +import { Type } from '../../common/core.types'; +import { NgModuleWithProviders } from '../../common/func.is-ng-module-def-with-providers'; export type BuilderData = { configDef: Map | InjectionToken, any>; diff --git a/lib/mock-component/mock-component.spec.ts b/lib/mock-component/mock-component.spec.ts index 35d58d7ee2..df5887f09a 100644 --- a/lib/mock-component/mock-component.spec.ts +++ b/lib/mock-component/mock-component.spec.ts @@ -10,8 +10,16 @@ import { ViewChild, ViewChildren, } from '@angular/core'; -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; -import { FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms'; +import { + async, + ComponentFixture, + TestBed, +} from '@angular/core/testing'; +import { + FormControl, + FormsModule, + ReactiveFormsModule, +} from '@angular/forms'; import { By } from '@angular/platform-browser'; import { staticTrue } from '../../tests'; @@ -41,11 +49,19 @@ import { MockedComponent } from './types'; (someOutput2)="emitted = $event" > - + - + doh - + ng-content body header @@ -55,12 +71,17 @@ import { MockedComponent } from './types'; block 2 body ng-content body footer - - child of element-with-content-only + + child of element-with-content-only `, }) export class ExampleComponentContainer { - @ViewChild(ChildComponent, staticTrue) public childComponent?: ChildComponent; + @ViewChild(ChildComponent, staticTrue) + public childComponent?: ChildComponent; public emitted = ''; public readonly formControl = new FormControl(''); @@ -99,64 +120,90 @@ describe('MockComponent', () => { it('should have use a selector of the original component', () => { fixture.detectChanges(); - const mockComponent = fixture.debugElement.query(By.css('simple-component')); + const mockComponent = fixture.debugElement.query( + By.css('simple-component'), + ); expect(mockComponent).not.toBeNull(); }); it('should have the input set on the mock component', () => { fixture.detectChanges(); - const mockComponent = fixture.debugElement.query(By.directive(SimpleComponent)).componentInstance; + const mockComponent = fixture.debugElement.query( + By.directive(SimpleComponent), + ).componentInstance; expect(mockComponent.someInput).toEqual('hi'); expect(mockComponent.someInput2).toEqual('bye'); }); it('has no issues with multiple decorators on an input', () => { fixture.detectChanges(); - const mockComponent = fixture.debugElement.query(By.directive(SimpleComponent)); + const mockComponent = fixture.debugElement.query( + By.directive(SimpleComponent), + ); expect(mockComponent.componentInstance.someInput3).toEqual(true); }); it('should trigger output bound behavior', () => { fixture.detectChanges(); - const mockComponent = fixture.debugElement.query(By.directive(SimpleComponent)).componentInstance; + const mockComponent = fixture.debugElement.query( + By.directive(SimpleComponent), + ).componentInstance; mockComponent.someOutput1.emit('hi'); expect(component.emitted).toEqual('hi'); }); it('should trigger output bound behavior for extended outputs', () => { fixture.detectChanges(); - const mockComponent = fixture.debugElement.query(By.directive(SimpleComponent)).componentInstance; + const mockComponent = fixture.debugElement.query( + By.directive(SimpleComponent), + ).componentInstance; mockComponent.someOutput2.emit('hi'); expect(component.emitted).toEqual('hi'); }); it('the mock should have an ng-content body', () => { fixture.detectChanges(); - const mockComponent = fixture.debugElement.query(By.css('#ng-content-component')); + const mockComponent = fixture.debugElement.query( + By.css('#ng-content-component'), + ); expect(mockComponent.nativeElement.innerText).toContain('doh'); }); it('should give each instance of a mock component its own event emitter', () => { - const mockComponents = fixture.debugElement.queryAll(By.directive(SimpleComponent)); + const mockComponents = fixture.debugElement.queryAll( + By.directive(SimpleComponent), + ); const mockComponent1 = mockComponents[0].componentInstance; const mockComponent2 = mockComponents[1].componentInstance; - expect(mockComponent1.someOutput1).not.toEqual(mockComponent2.someOutput1); + expect(mockComponent1.someOutput1).not.toEqual( + mockComponent2.someOutput1, + ); }); it('should work with components w/o inputs or outputs', () => { - const mockComponent = fixture.debugElement.query(By.directive(EmptyComponent)); + const mockComponent = fixture.debugElement.query( + By.directive(EmptyComponent), + ); expect(mockComponent).not.toBeNull(); }); it('should allow ngModel bindings', () => { - const mockComponent = fixture.debugElement.query(By.css('#ngmodel-component')); + const mockComponent = fixture.debugElement.query( + By.css('#ngmodel-component'), + ); expect(mockComponent).not.toBeNull(); }); it('should memoize the return value by argument', () => { - expect(MockComponent(EmptyComponent)).toBe(MockComponent(EmptyComponent)); - expect(MockComponent(SimpleComponent)).toBe(MockComponent(SimpleComponent)); - expect(MockComponent(EmptyComponent)).not.toBe(MockComponent(SimpleComponent)); + expect(MockComponent(EmptyComponent)).toBe( + MockComponent(EmptyComponent), + ); + expect(MockComponent(SimpleComponent)).toBe( + MockComponent(SimpleComponent), + ); + expect(MockComponent(EmptyComponent)).not.toBe( + MockComponent(SimpleComponent), + ); }); it('should set ViewChild components correctly', () => { @@ -165,7 +212,9 @@ describe('MockComponent', () => { }); it('should allow spying of viewchild component methods', () => { - const spy = component.childComponent ? component.childComponent.performAction : null; + const spy = component.childComponent + ? component.childComponent.performAction + : null; component.performActionOnChild('test'); expect(spy).toHaveBeenCalledWith('test'); }); @@ -210,43 +259,61 @@ describe('MockComponent', () => { fixture.detectChanges(); // a mock component with @ViewChild was created without errors. - const templateOutlet = fixture.debugElement.query(By.css('#element-with-content-and-template')); + const templateOutlet = fixture.debugElement.query( + By.css('#element-with-content-and-template'), + ); expect(templateOutlet).toBeTruthy(); // looking for ng-content. const ngContent = templateOutlet; expect(ngContent).toBeTruthy(); - expect(ngContent.nativeElement.innerText.replace(/\s+/gim, ' ').trim()).toEqual( - 'ng-content body header ng-content body footer', - ); + expect( + ngContent.nativeElement.innerText + .replace(/\s+/gim, ' ') + .trim(), + ).toEqual('ng-content body header ng-content body footer'); // looking for 1st templateRef. block1 = templateOutlet.query(By.css('[data-key="block1"]')); expect(block1).toBeFalsy(); - (templateOutlet.componentInstance as MockedComponent).__render('block1'); + (templateOutlet.componentInstance as MockedComponent).__render( + 'block1', + ); block1 = templateOutlet.query(By.css('[data-key="block1"]')); expect(block1).toBeTruthy(); - expect(block1.nativeElement.innerText.trim()).toEqual('block 1 body'); + expect(block1.nativeElement.innerText.trim()).toEqual( + 'block 1 body', + ); // looking for 2nd templateRef. block2 = templateOutlet.query(By.css('[data-key="block2"]')); expect(block2).toBeFalsy(); - (templateOutlet.componentInstance as MockedComponent).__render('block2'); + (templateOutlet.componentInstance as MockedComponent).__render( + 'block2', + ); block2 = templateOutlet.query(By.css('[data-key="block2"]')); expect(block2).toBeTruthy(); - expect(block2.nativeElement.innerText.trim()).toEqual('block 2 body'); + expect(block2.nativeElement.innerText.trim()).toEqual( + 'block 2 body', + ); // looking for 3rd templateRef. block3 = templateOutlet.query(By.css('[data-key="block3"]')); expect(block3).toBeFalsy(); - (templateOutlet.componentInstance as MockedComponent).__render('block3'); + (templateOutlet.componentInstance as MockedComponent).__render( + 'block3', + ); fixture.detectChanges(); block3 = templateOutlet.query(By.css('[data-key="block3"]')); expect(block3).toBeTruthy(); expect(block3.nativeElement.innerText.trim()).toEqual(''); - (templateOutlet.componentInstance as MockedComponent).__hide('block3'); + (templateOutlet.componentInstance as MockedComponent).__hide( + 'block3', + ); fixture.detectChanges(); - expect(templateOutlet.query(By.css('[data-key="block3"]'))).toBeFalsy(); + expect( + templateOutlet.query(By.css('[data-key="block3"]')), + ).toBeFalsy(); }); it('ignores missed blocks', () => { @@ -264,7 +331,9 @@ describe('MockComponent', () => { fixture.detectChanges(); // a mock component was created without errors. - const templateOutlet = fixture.debugElement.query(By.css('#element-without-content-and-template')); + const templateOutlet = fixture.debugElement.query( + By.css('#element-without-content-and-template'), + ); expect(templateOutlet).toBeTruthy(); expect(templateOutlet.nativeElement.innerHTML).toBeFalsy(); }); @@ -273,11 +342,15 @@ describe('MockComponent', () => { fixture.detectChanges(); // a mock component was created without errors. - const templateOutlet = fixture.debugElement.query(By.css('#element-with-content-only')); + const templateOutlet = fixture.debugElement.query( + By.css('#element-with-content-only'), + ); expect(templateOutlet).toBeTruthy(); // content has right value - expect(templateOutlet.nativeElement.innerHTML.trim()).toEqual('child of element-with-content-only'); + expect(templateOutlet.nativeElement.innerHTML.trim()).toEqual( + 'child of element-with-content-only', + ); }); }); @@ -286,15 +359,23 @@ describe('MockComponent', () => { template: '', }) class MyClass { - @ContentChild('i1', { read: true } as any) public o1?: TemplateRef; - @ContentChildren('i2', { read: true } as any) public o2?: TemplateRef; - @ViewChild('i3', { read: true } as any) public o3?: QueryList; - @ViewChildren('i4', { read: true } as any) public o4?: QueryList; - - @ContentChild('i5', { read: false } as any) public o5?: TemplateRef; - @ContentChildren('i6', { read: false } as any) public o6?: TemplateRef; - @ViewChild('i7', { read: false } as any) public o7?: QueryList; - @ViewChildren('i8', { read: false } as any) public o8?: QueryList; + @ContentChild('i1', { read: true } as any) + public o1?: TemplateRef; + @ContentChildren('i2', { read: true } as any) + public o2?: TemplateRef; + @ViewChild('i3', { read: true } as any) + public o3?: QueryList; + @ViewChildren('i4', { read: true } as any) + public o4?: QueryList; + + @ContentChild('i5', { read: false } as any) + public o5?: TemplateRef; + @ContentChildren('i6', { read: false } as any) + public o6?: TemplateRef; + @ViewChild('i7', { read: false } as any) + public o7?: QueryList; + @ViewChildren('i8', { read: false } as any) + public o8?: QueryList; } const actual = MockComponent(MyClass) as any; diff --git a/lib/mock-declaration/mock-declaration.spec.ts b/lib/mock-declaration/mock-declaration.spec.ts index e42105b809..24ccd81d75 100644 --- a/lib/mock-declaration/mock-declaration.spec.ts +++ b/lib/mock-declaration/mock-declaration.spec.ts @@ -1,6 +1,14 @@ -import { Component, Directive, Pipe, PipeTransform } from '@angular/core'; +import { + Component, + Directive, + Pipe, + PipeTransform, +} from '@angular/core'; -import { MockDeclaration, MockDeclarations } from './mock-declaration'; +import { + MockDeclaration, + MockDeclarations, +} from './mock-declaration'; @Component({ selector: 'empty-template-container', @@ -30,7 +38,11 @@ class Target { describe('MockDeclaration', () => { it('should process a set correctly', () => { - const mocks: any[] = MockDeclarations(TargetComponent, TargetDirective, TargetPipe); + const mocks: any[] = MockDeclarations( + TargetComponent, + TargetDirective, + TargetPipe, + ); expect(mocks.length).toEqual(3); expect(mocks[0].nameConstructor).toEqual('ComponentMock'); expect(mocks[1].nameConstructor).toEqual('DirectiveMock'); diff --git a/lib/mock-directive/mock-directive.spec.ts b/lib/mock-directive/mock-directive.spec.ts index c38881a9fb..280665ef80 100644 --- a/lib/mock-directive/mock-directive.spec.ts +++ b/lib/mock-directive/mock-directive.spec.ts @@ -14,7 +14,11 @@ import { ViewChild, ViewChildren, } from '@angular/core'; -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { + async, + ComponentFixture, + TestBed, +} from '@angular/core/testing'; import { FormControl, FormControlDirective } from '@angular/forms'; import { By } from '@angular/platform-browser'; @@ -83,15 +87,26 @@ class GettersAndSettersDirective { @Component({ selector: 'example-component-container', template: ` -
    +
    -
    hi
    +
    + hi +
    `, }) class ExampleComponentContainer { - @ViewChild(ExampleDirective, staticFalse) public childDirective?: ExampleDirective; + @ViewChild(ExampleDirective, staticFalse) + public childDirective?: ExampleDirective; public emitted = false; public readonly foo = new FormControl(''); @@ -125,19 +140,25 @@ describe('MockDirective', () => { }); it('should have use a selector of the original component', () => { - const element = fixture.debugElement.query(By.directive(ExampleDirective)); + const element = fixture.debugElement.query( + By.directive(ExampleDirective), + ); expect(element).not.toBeNull(); }); it('should have the input set on the mock component', () => { - const debugElement = fixture.debugElement.query(By.directive(ExampleDirective)); + const debugElement = fixture.debugElement.query( + By.directive(ExampleDirective), + ); const element = debugElement.injector.get(ExampleDirective); expect(element.something).toEqual('hi'); expect(element.exampleDirective).toEqual('bye'); }); it('triggers output bound behavior for extended outputs', () => { - const debugElement = fixture.debugElement.query(By.directive(ExampleDirective)); + const debugElement = fixture.debugElement.query( + By.directive(ExampleDirective), + ); const element = debugElement.injector.get(ExampleDirective); element.someOutput.emit(true); @@ -145,8 +166,12 @@ describe('MockDirective', () => { }); it('should memoize the return value by argument', () => { - expect(MockDirective(ExampleDirective)).toEqual(MockDirective(ExampleDirective)); - expect(MockDirective(ExampleDirective)).not.toEqual(ExampleDirective); + expect(MockDirective(ExampleDirective)).toEqual( + MockDirective(ExampleDirective), + ); + expect(MockDirective(ExampleDirective)).not.toEqual( + ExampleDirective, + ); }); it('can mock formControlDirective from angular', () => { @@ -154,7 +179,9 @@ describe('MockDirective', () => { // I found that FormControlDirective is one of those weird directives. // Since I don't know how they did it, I don't know how to test it except to write this // Test around a known-odd directive. - const debugElement = fixture.debugElement.query(By.directive(ExampleDirective)); + const debugElement = fixture.debugElement.query( + By.directive(ExampleDirective), + ); expect(debugElement).not.toBeNull(); }); @@ -169,23 +196,31 @@ describe('MockDirective', () => { fixture.detectChanges(); expect(mockDirective.exampleStructuralDirective).toBeTruthy(); - const debugElement = fixture.debugElement.query(By.css('#example-structural-directive')); + const debugElement = fixture.debugElement.query( + By.css('#example-structural-directive'), + ); expect(debugElement.nativeElement.innerHTML).toContain('hi'); }); it('renders with true', async () => { - await MockBuilder(ExampleComponentContainer).mock(ExampleStructuralDirective, { - render: true, - }); + await MockBuilder(ExampleComponentContainer).mock( + ExampleStructuralDirective, + { + render: true, + }, + ); expect(() => MockRender(ExampleComponentContainer)).not.toThrow(); }); it('renders with $implicit', async () => { - await MockBuilder(ExampleComponentContainer).mock(ExampleStructuralDirective, { - render: { - $implicit: true, + await MockBuilder(ExampleComponentContainer).mock( + ExampleStructuralDirective, + { + render: { + $implicit: true, + }, }, - }); + ); expect(() => MockRender(ExampleComponentContainer)).not.toThrow(); }); @@ -195,7 +230,9 @@ describe('MockDirective', () => { }); it('should allow spying of viewchild directive methods', () => { - const spy = component.childDirective ? component.childDirective.performAction : null; + const spy = component.childDirective + ? component.childDirective.performAction + : null; component.performActionOnChild('test'); expect(spy).toHaveBeenCalledWith('test'); }); @@ -213,10 +250,17 @@ describe('MockDirective', () => { }); it('mocks several directives', () => { - const mocks = MockDirectives(GettersAndSettersDirective, ExampleStructuralDirective); + const mocks = MockDirectives( + GettersAndSettersDirective, + ExampleStructuralDirective, + ); expect(mocks.length).toEqual(2); - expect(isMockedNgDefOf(mocks[0], GettersAndSettersDirective, 'd')).toBeTruthy(); - expect(isMockedNgDefOf(mocks[1], ExampleStructuralDirective, 'd')).toBeTruthy(); + expect( + isMockedNgDefOf(mocks[0], GettersAndSettersDirective, 'd'), + ).toBeTruthy(); + expect( + isMockedNgDefOf(mocks[1], ExampleStructuralDirective, 'd'), + ).toBeTruthy(); }); it('A9 correct mocking of ContentChild, ContentChildren, ViewChild, ViewChildren ISSUE #109', () => { @@ -224,15 +268,23 @@ describe('MockDirective', () => { selector: 'never', }) class MyClass { - @ContentChild('i1', { read: true } as any) public o1?: TemplateRef; - @ContentChildren('i2', { read: true } as any) public o2?: TemplateRef; - @ViewChild('i3', { read: true } as any) public o3?: QueryList; - @ViewChildren('i4', { read: true } as any) public o4?: QueryList; - - @ContentChild('i5', { read: false } as any) public o5?: TemplateRef; - @ContentChildren('i6', { read: false } as any) public o6?: TemplateRef; - @ViewChild('i7', { read: false } as any) public o7?: QueryList; - @ViewChildren('i8', { read: false } as any) public o8?: QueryList; + @ContentChild('i1', { read: true } as any) + public o1?: TemplateRef; + @ContentChildren('i2', { read: true } as any) + public o2?: TemplateRef; + @ViewChild('i3', { read: true } as any) + public o3?: QueryList; + @ViewChildren('i4', { read: true } as any) + public o4?: QueryList; + + @ContentChild('i5', { read: false } as any) + public o5?: TemplateRef; + @ContentChildren('i6', { read: false } as any) + public o6?: TemplateRef; + @ViewChild('i7', { read: false } as any) + public o7?: QueryList; + @ViewChildren('i8', { read: false } as any) + public o8?: QueryList; } const actual = MockDirective(MyClass) as any; diff --git a/lib/mock-helper/mock-helper.guts.spec.ts b/lib/mock-helper/mock-helper.guts.spec.ts index 00bbec295e..8dbe34dbf9 100644 --- a/lib/mock-helper/mock-helper.guts.spec.ts +++ b/lib/mock-helper/mock-helper.guts.spec.ts @@ -53,20 +53,26 @@ class Target2Component {} @Component({ selector: 'target1', - template: `
    {{ greeting | target1 }} {{ target }}
    `, + template: `
    + {{ greeting | target1 }} {{ target }} +
    `, }) class Target1Component { @Input() public readonly greeting: string | null = null; - @Output() public readonly update: EventEmitter = new EventEmitter(); + @Output() + public readonly update: EventEmitter = new EventEmitter(); - public constructor(@Inject(TARGET1) public readonly target: string) {} + public constructor( + @Inject(TARGET1) public readonly target: string, + ) {} } @Directive({ selector: '[target1]', }) class Target1Directive implements OnDestroy { - @Output() public readonly target1: EventEmitter = new EventEmitter(); + @Output() + public readonly target1: EventEmitter = new EventEmitter(); public constructor(public readonly service: Target1Service) { this.service.callback = () => this.target1.emit(); @@ -128,18 +134,36 @@ describe('mock-helper.guts', () => { expect(ngModule.declarations?.length).toEqual(3); if (ngModule.declarations) { expect(isNgDef(ngModule.declarations[0], 'p')).toBeTruthy(); - expect(isMockedNgDefOf(ngModule.declarations[0], Target1Pipe, 'p')).toBeTruthy(); + expect( + isMockedNgDefOf(ngModule.declarations[0], Target1Pipe, 'p'), + ).toBeTruthy(); expect(isNgDef(ngModule.declarations[1], 'c')).toBeTruthy(); - expect(isMockedNgDefOf(ngModule.declarations[1], Target1Component, 'c')).toBeFalsy(); + expect( + isMockedNgDefOf( + ngModule.declarations[1], + Target1Component, + 'c', + ), + ).toBeFalsy(); expect(isNgDef(ngModule.declarations[2], 'd')).toBeTruthy(); - expect(isMockedNgDefOf(ngModule.declarations[2], Target1Directive, 'd')).toBeTruthy(); + expect( + isMockedNgDefOf( + ngModule.declarations[2], + Target1Directive, + 'd', + ), + ).toBeTruthy(); } expect(ngModule.imports?.length).toEqual(2); if (ngModule.imports) { expect(isNgDef(ngModule.imports[0], 'm')).toBeTruthy(); - expect(isMockedNgDefOf(ngModule.imports[0], CommonModule, 'm')).toBeFalsy(); + expect( + isMockedNgDefOf(ngModule.imports[0], CommonModule, 'm'), + ).toBeFalsy(); expect(isNgDef(ngModule.imports[1], 'm')).toBeTruthy(); - expect(isMockedNgDefOf(ngModule.imports[1], Target2Module, 'm')).toBeTruthy(); + expect( + isMockedNgDefOf(ngModule.imports[1], Target2Module, 'm'), + ).toBeTruthy(); } expect(ngModule.providers?.length).toEqual(2); if (ngModule.providers) { @@ -160,7 +184,9 @@ describe('mock-helper.guts', () => { expect(ngModule.imports?.length).toEqual(1); if (ngModule.imports) { expect(isNgDef(ngModule.imports[0], 'm')).toBeTruthy(); - expect(isMockedNgDefOf(ngModule.imports[0], Target1Module, 'm')).toBeFalsy(); + expect( + isMockedNgDefOf(ngModule.imports[0], Target1Module, 'm'), + ).toBeFalsy(); } }); @@ -172,7 +198,13 @@ describe('mock-helper.guts', () => { expect(ngModule.imports?.length).toEqual(1); if (ngModule.imports) { expect(isNgDef(ngModule.imports[0].ngModule, 'm')).toBeTruthy(); - expect(isMockedNgDefOf(ngModule.imports[0].ngModule, Target1Module, 'm')).toBeFalsy(); + expect( + isMockedNgDefOf( + ngModule.imports[0].ngModule, + Target1Module, + 'm', + ), + ).toBeFalsy(); } }); @@ -181,7 +213,13 @@ describe('mock-helper.guts', () => { expect(ngModule.declarations?.length).toEqual(1); if (ngModule.declarations) { expect(isNgDef(ngModule.declarations[0], 'c')).toBeTruthy(); - expect(isMockedNgDefOf(ngModule.declarations[0], Target1Component, 'c')).toBeFalsy(); + expect( + isMockedNgDefOf( + ngModule.declarations[0], + Target1Component, + 'c', + ), + ).toBeFalsy(); } }); @@ -190,7 +228,13 @@ describe('mock-helper.guts', () => { expect(ngModule.declarations?.length).toEqual(1); if (ngModule.declarations) { expect(isNgDef(ngModule.declarations[0], 'd')).toBeTruthy(); - expect(isMockedNgDefOf(ngModule.declarations[0], Target1Directive, 'd')).toBeFalsy(); + expect( + isMockedNgDefOf( + ngModule.declarations[0], + Target1Directive, + 'd', + ), + ).toBeFalsy(); } }); @@ -199,7 +243,9 @@ describe('mock-helper.guts', () => { expect(ngModule.declarations?.length).toEqual(1); if (ngModule.declarations) { expect(isNgDef(ngModule.declarations[0], 'p')).toBeTruthy(); - expect(isMockedNgDefOf(ngModule.declarations[0], Target1Pipe, 'p')).toBeFalsy(); + expect( + isMockedNgDefOf(ngModule.declarations[0], Target1Pipe, 'p'), + ).toBeFalsy(); } }); @@ -226,7 +272,10 @@ describe('mock-helper.guts', () => { }); it('keeps tokens', () => { - const ngModule = ngMocks.guts(TARGET1, { provide: TARGET1, useValue: 123 }); + const ngModule = ngMocks.guts(TARGET1, { + provide: TARGET1, + useValue: 123, + }); expect(ngModule.providers?.length).toEqual(1); if (ngModule.providers) { expect(ngModule.providers[0]).toEqual({ @@ -246,7 +295,9 @@ describe('mock-helper.guts', () => { expect(ngModule.imports?.length).toEqual(2); if (ngModule.imports) { expect(ngModule.imports[0]).toBe(CommonModule); - expect(isMockedNgDefOf(ngModule.imports[1], Target2Module, 'm')).toBeTruthy(); + expect( + isMockedNgDefOf(ngModule.imports[1], Target2Module, 'm'), + ).toBeTruthy(); } }); @@ -258,7 +309,13 @@ describe('mock-helper.guts', () => { expect(ngModule.imports?.length).toEqual(1); if (ngModule.imports) { expect(isNgDef(ngModule.imports[0].ngModule, 'm')).toBeTruthy(); - expect(isMockedNgDefOf(ngModule.imports[0].ngModule, Target1Module, 'm')).toBeTruthy(); + expect( + isMockedNgDefOf( + ngModule.imports[0].ngModule, + Target1Module, + 'm', + ), + ).toBeTruthy(); } }); @@ -267,7 +324,13 @@ describe('mock-helper.guts', () => { expect(ngModule.declarations?.length).toEqual(1); if (ngModule.declarations) { expect(isNgDef(ngModule.declarations[0], 'c')).toBeTruthy(); - expect(isMockedNgDefOf(ngModule.declarations[0], Target1Component, 'c')).toBeTruthy(); + expect( + isMockedNgDefOf( + ngModule.declarations[0], + Target1Component, + 'c', + ), + ).toBeTruthy(); } }); @@ -276,7 +339,13 @@ describe('mock-helper.guts', () => { expect(ngModule.declarations?.length).toEqual(1); if (ngModule.declarations) { expect(isNgDef(ngModule.declarations[0], 'd')).toBeTruthy(); - expect(isMockedNgDefOf(ngModule.declarations[0], Target1Directive, 'd')).toBeTruthy(); + expect( + isMockedNgDefOf( + ngModule.declarations[0], + Target1Directive, + 'd', + ), + ).toBeTruthy(); } }); @@ -285,7 +354,9 @@ describe('mock-helper.guts', () => { expect(ngModule.declarations?.length).toEqual(1); if (ngModule.declarations) { expect(isNgDef(ngModule.declarations[0], 'p')).toBeTruthy(); - expect(isMockedNgDefOf(ngModule.declarations[0], Target1Pipe, 'p')).toBeTruthy(); + expect( + isMockedNgDefOf(ngModule.declarations[0], Target1Pipe, 'p'), + ).toBeTruthy(); } }); @@ -302,7 +373,10 @@ describe('mock-helper.guts', () => { }); it('mocks tokens', () => { - const ngModule = ngMocks.guts(TARGET2, { provide: TARGET1, useValue: 123 }); + const ngModule = ngMocks.guts(TARGET2, { + provide: TARGET1, + useValue: 123, + }); expect(ngModule.providers?.length).toEqual(1); if (ngModule.providers) { expect(ngModule.providers[0]).toEqual({ @@ -326,7 +400,13 @@ describe('mock-helper.guts', () => { expect(ngModule.imports?.length).toEqual(1); if (ngModule.imports) { expect(isNgDef(ngModule.imports[0].ngModule, 'm')).toBeTruthy(); - expect(isMockedNgDefOf(ngModule.imports[0].ngModule, Target1Module, 'm')).toBeTruthy(); + expect( + isMockedNgDefOf( + ngModule.imports[0].ngModule, + Target1Module, + 'm', + ), + ).toBeTruthy(); } }); @@ -339,16 +419,24 @@ describe('mock-helper.guts', () => { }); it('skips an existing mock module', () => { - const ngModule = ngMocks.guts(null, [Target1Module, Target1CopyModule]); + const ngModule = ngMocks.guts(null, [ + Target1Module, + Target1CopyModule, + ]); expect(ngModule.imports?.length).toEqual(2); if (ngModule.imports) { expect(ngModule.imports[0]).toBe(CommonModule); - expect(ngModule.imports[1]).toBe(getMockedNgDefOf(Target2Module)); + expect(ngModule.imports[1]).toBe( + getMockedNgDefOf(Target2Module), + ); } }); it('skips 2nd kept module', () => { - const ngModule = ngMocks.guts(Target2Module, [Target1Module, Target1CopyModule]); + const ngModule = ngMocks.guts(Target2Module, [ + Target1Module, + Target1CopyModule, + ]); expect(ngModule.imports?.length).toEqual(2); if (ngModule.imports) { expect(ngModule.imports[0]).toBe(CommonModule); @@ -357,20 +445,30 @@ describe('mock-helper.guts', () => { }); it('skips the 2nd mock module', () => { - const ngModule = ngMocks.guts(TARGET1, [Target1Module, Target1CopyModule]); + const ngModule = ngMocks.guts(TARGET1, [ + Target1Module, + Target1CopyModule, + ]); expect(ngModule.imports?.length).toEqual(2); if (ngModule.imports) { expect(ngModule.imports[0]).toBe(CommonModule); - expect(isMockedNgDefOf(ngModule.imports[1], Target2Module, 'm')).toBeTruthy(); + expect( + isMockedNgDefOf(ngModule.imports[1], Target2Module, 'm'), + ).toBeTruthy(); } }); it('skips the 2nd nested mock module', () => { - const ngModule = ngMocks.guts(TARGET1, [Target1Module, Target3Module]); + const ngModule = ngMocks.guts(TARGET1, [ + Target1Module, + Target3Module, + ]); expect(ngModule.imports?.length).toEqual(2); if (ngModule.imports) { expect(ngModule.imports[0]).toBe(CommonModule); - expect(isMockedNgDefOf(ngModule.imports[1], Target2Module, 'm')).toBeTruthy(); + expect( + isMockedNgDefOf(ngModule.imports[1], Target2Module, 'm'), + ).toBeTruthy(); } }); @@ -404,12 +502,21 @@ describe('mock-helper.guts', () => { ]); expect(ngModule.imports?.length).toEqual(1); if (ngModule.imports) { - expect(isMockedNgDefOf(ngModule.imports[0].ngModule, Target1Module, 'm')).toBeTruthy(); + expect( + isMockedNgDefOf( + ngModule.imports[0].ngModule, + Target1Module, + 'm', + ), + ).toBeTruthy(); } }); it('skips 2nd kept component', () => { - const ngModule = ngMocks.guts(Target1Component, [Target1Component, Target1Component]); + const ngModule = ngMocks.guts(Target1Component, [ + Target1Component, + Target1Component, + ]); expect(ngModule.declarations?.length).toEqual(1); if (ngModule.declarations) { expect(ngModule.declarations[0]).toBe(Target1Component); @@ -417,15 +524,27 @@ describe('mock-helper.guts', () => { }); it('skips the 2nd mock component', () => { - const ngModule = ngMocks.guts(TARGET1, [Target1Component, Target1Component]); + const ngModule = ngMocks.guts(TARGET1, [ + Target1Component, + Target1Component, + ]); expect(ngModule.declarations?.length).toEqual(1); if (ngModule.declarations) { - expect(isMockedNgDefOf(ngModule.declarations[0], Target1Component, 'c')).toBeTruthy(); + expect( + isMockedNgDefOf( + ngModule.declarations[0], + Target1Component, + 'c', + ), + ).toBeTruthy(); } }); it('skips 2nd kept directive', () => { - const ngModule = ngMocks.guts(Target1Directive, [Target1Directive, Target1Directive]); + const ngModule = ngMocks.guts(Target1Directive, [ + Target1Directive, + Target1Directive, + ]); expect(ngModule.declarations?.length).toEqual(1); if (ngModule.declarations) { expect(ngModule.declarations[0]).toBe(Target1Directive); @@ -433,15 +552,27 @@ describe('mock-helper.guts', () => { }); it('skips the 2nd mock directive', () => { - const ngModule = ngMocks.guts(TARGET1, [Target1Directive, Target1Directive]); + const ngModule = ngMocks.guts(TARGET1, [ + Target1Directive, + Target1Directive, + ]); expect(ngModule.declarations?.length).toEqual(1); if (ngModule.declarations) { - expect(isMockedNgDefOf(ngModule.declarations[0], Target1Directive, 'd')).toBeTruthy(); + expect( + isMockedNgDefOf( + ngModule.declarations[0], + Target1Directive, + 'd', + ), + ).toBeTruthy(); } }); it('skips 2nd kept pipe', () => { - const ngModule = ngMocks.guts(Target1Pipe, [Target1Pipe, Target1Pipe]); + const ngModule = ngMocks.guts(Target1Pipe, [ + Target1Pipe, + Target1Pipe, + ]); expect(ngModule.declarations?.length).toEqual(1); if (ngModule.declarations) { expect(ngModule.declarations[0]).toBe(Target1Pipe); @@ -449,15 +580,23 @@ describe('mock-helper.guts', () => { }); it('skips the 2nd mock pipe', () => { - const ngModule = ngMocks.guts(TARGET1, [Target1Pipe, Target1Pipe]); + const ngModule = ngMocks.guts(TARGET1, [ + Target1Pipe, + Target1Pipe, + ]); expect(ngModule.declarations?.length).toEqual(1); if (ngModule.declarations) { - expect(isMockedNgDefOf(ngModule.declarations[0], Target1Pipe, 'p')).toBeTruthy(); + expect( + isMockedNgDefOf(ngModule.declarations[0], Target1Pipe, 'p'), + ).toBeTruthy(); } }); it('skips 2nd kept service', () => { - const ngModule = ngMocks.guts(Target1Service, [Target1Service, Target1Service]); + const ngModule = ngMocks.guts(Target1Service, [ + Target1Service, + Target1Service, + ]); expect(ngModule.providers?.length).toEqual(1); if (ngModule.providers) { expect(ngModule.providers[0]).toBe(Target1Service); @@ -465,7 +604,10 @@ describe('mock-helper.guts', () => { }); it('skips the 2nd mock service', () => { - const ngModule = ngMocks.guts(TARGET1, [Target1Service, Target1Service]); + const ngModule = ngMocks.guts(TARGET1, [ + Target1Service, + Target1Service, + ]); expect(ngModule.providers?.length).toEqual(1); if (ngModule.providers) { expect(ngModule.providers[0]).toEqual({ @@ -541,7 +683,10 @@ describe('mock-helper.guts', () => { }); it('excludes 2nd nested kept module', () => { - const ngModule = ngMocks.guts(Target2Module, [Target1Module, Target3Module]); + const ngModule = ngMocks.guts(Target2Module, [ + Target1Module, + Target3Module, + ]); expect(ngModule).toEqual( jasmine.objectContaining({ imports: [CommonModule, Target2Module], @@ -550,7 +695,10 @@ describe('mock-helper.guts', () => { }); it('excludes the 2nd mock kept module', () => { - const ngModule = ngMocks.guts(null, [Target1Module, Target3Module]); + const ngModule = ngMocks.guts(null, [ + Target1Module, + Target3Module, + ]); expect(ngModule).toEqual( jasmine.objectContaining({ imports: [CommonModule, getMockedNgDefOf(Target2Module)], @@ -574,7 +722,10 @@ describe('mock-helper.guts', () => { [Target1Pipe, Target1Pipe], ); expect(ngModule).toEqual({ - declarations: [getMockedNgDefOf(Target1Component), getMockedNgDefOf(Target1Directive)], + declarations: [ + getMockedNgDefOf(Target1Component), + getMockedNgDefOf(Target1Directive), + ], imports: [CommonModule, getMockedNgDefOf(Target2Module)], providers: [ Target1Service, @@ -587,7 +738,11 @@ describe('mock-helper.guts', () => { }); it('excludes mock providers', () => { - const ngModule = ngMocks.guts(null, Target1Service, Target1Service); + const ngModule = ngMocks.guts( + null, + Target1Service, + Target1Service, + ); expect(ngModule).toEqual({ declarations: [], imports: [], @@ -596,7 +751,11 @@ describe('mock-helper.guts', () => { }); it('excludes mock module with providers', () => { - const ngModule = ngMocks.guts(null, { ngModule: Target1Module, providers: [] }, Target1Module); + const ngModule = ngMocks.guts( + null, + { ngModule: Target1Module, providers: [] }, + Target1Module, + ); expect(ngModule).toEqual({ declarations: [], imports: [], @@ -614,7 +773,11 @@ describe('mock-helper.guts', () => { }); it('excludes nested kept module', () => { - const ngModule = ngMocks.guts(Target2Module, Target3Module, Target2Module); + const ngModule = ngMocks.guts( + Target2Module, + Target3Module, + Target2Module, + ); expect(ngModule).toEqual({ declarations: [], imports: [CommonModule], @@ -632,7 +795,11 @@ describe('mock-helper.guts', () => { }); it('excludes mock component', () => { - const ngModule = ngMocks.guts(null, Target1Component, Target1Component); + const ngModule = ngMocks.guts( + null, + Target1Component, + Target1Component, + ); expect(ngModule).toEqual({ declarations: [], imports: [], @@ -641,7 +808,11 @@ describe('mock-helper.guts', () => { }); it('excludes mock directive', () => { - const ngModule = ngMocks.guts(null, Target1Directive, Target1Directive); + const ngModule = ngMocks.guts( + null, + Target1Directive, + Target1Directive, + ); expect(ngModule).toEqual({ declarations: [], imports: [], @@ -660,9 +831,23 @@ describe('mock-helper.guts', () => { it('excludes kept declarations', () => { const ngModule = ngMocks.guts( - [Target1Module, Target1Component, Target1Directive, Target1Pipe, Target1Service, TARGET1], + [ + Target1Module, + Target1Component, + Target1Directive, + Target1Pipe, + Target1Service, + TARGET1, + ], null, - [Target1Module, Target1Component, Target1Directive, Target1Pipe, Target1Service, TARGET1], + [ + Target1Module, + Target1Component, + Target1Directive, + Target1Pipe, + Target1Service, + TARGET1, + ], ); expect(ngModule).toEqual({ declarations: [], diff --git a/lib/mock-helper/mock-helper.spec.ts b/lib/mock-helper/mock-helper.spec.ts index 64683c6812..f0b4c16788 100644 --- a/lib/mock-helper/mock-helper.spec.ts +++ b/lib/mock-helper/mock-helper.spec.ts @@ -1,6 +1,12 @@ // tslint:disable max-file-line-count -import { Component, Directive, EventEmitter, Input, Output } from '@angular/core'; +import { + Component, + Directive, + EventEmitter, + Input, + Output, +} from '@angular/core'; import { async, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; @@ -65,11 +71,16 @@ describe('MockHelper:getDirective', () => { `); // Looking for original. - const debugElement = fixture.debugElement.query(By.directive(ExampleDirective)); + const debugElement = fixture.debugElement.query( + By.directive(ExampleDirective), + ); const element = debugElement.injector.get(ExampleDirective); // Using helper. - const elementFromHelper = ngMocks.get(fixture.debugElement.query(By.css('div')), ExampleDirective); + const elementFromHelper = ngMocks.get( + fixture.debugElement.query(By.css('div')), + ExampleDirective, + ); // Verification. expect(elementFromHelper).toBe(element); @@ -81,7 +92,10 @@ describe('MockHelper:getDirective', () => { `); // we need to render mock structural directives manually - for (const instance of ngMocks.findInstances(fixture.debugElement, ExampleStructuralDirective)) { + for (const instance of ngMocks.findInstances( + fixture.debugElement, + ExampleStructuralDirective, + )) { if (isMockOf(instance, ExampleStructuralDirective, 'd')) { instance.__render(); } @@ -89,14 +103,19 @@ describe('MockHelper:getDirective', () => { fixture.detectChanges(); // Using helper. - const elementFromHelper = ngMocks.get(fixture.debugElement.query(By.css('div')), ExampleStructuralDirective); + const elementFromHelper = ngMocks.get( + fixture.debugElement.query(By.css('div')), + ExampleStructuralDirective, + ); expect(elementFromHelper).toBeTruthy(); if (!elementFromHelper) { return; } // Verification. - expect(elementFromHelper.exampleStructuralDirective).toEqual(false); + expect(elementFromHelper.exampleStructuralDirective).toEqual( + false, + ); }); it('should return right structural directive via getDirectiveOrFail', () => { @@ -105,7 +124,10 @@ describe('MockHelper:getDirective', () => { `); // we need to render mock structural directives manually - for (const instance of ngMocks.findInstances(fixture.debugElement, ExampleStructuralDirective)) { + for (const instance of ngMocks.findInstances( + fixture.debugElement, + ExampleStructuralDirective, + )) { if (isMockOf(instance, ExampleStructuralDirective, 'd')) { instance.__render(); } @@ -113,16 +135,23 @@ describe('MockHelper:getDirective', () => { fixture.detectChanges(); // Using helper. - const elementFromHelper = ngMocks.get(fixture.debugElement.query(By.css('div')), ExampleStructuralDirective); + const elementFromHelper = ngMocks.get( + fixture.debugElement.query(By.css('div')), + ExampleStructuralDirective, + ); // Verification. - expect(elementFromHelper.exampleStructuralDirective).toEqual(false); + expect(elementFromHelper.exampleStructuralDirective).toEqual( + false, + ); }); it('find selector: T', () => { const fixture = MockRender(``); const componentA = ngMocks.find(fixture.debugElement, AComponent); - expect(componentA.componentInstance).toEqual(jasmine.any(AComponent)); + expect(componentA.componentInstance).toEqual( + jasmine.any(AComponent), + ); expect(() => ngMocks.find(componentA, BComponent)).toThrowError( 'Cannot find an element via ngMocks.find(BComponent)', @@ -131,8 +160,13 @@ describe('MockHelper:getDirective', () => { it('find selector: string', () => { const fixture = MockRender(``); - const componentB = ngMocks.find(fixture.debugElement, 'component-b'); - expect(componentB.componentInstance).toEqual(jasmine.any(BComponent)); + const componentB = ngMocks.find( + fixture.debugElement, + 'component-b', + ); + expect(componentB.componentInstance).toEqual( + jasmine.any(BComponent), + ); expect(() => ngMocks.find(componentB, AComponent)).toThrowError( 'Cannot find an element via ngMocks.find(AComponent)', @@ -142,58 +176,99 @@ describe('MockHelper:getDirective', () => { it('find selector: T', () => { const fixture = MockRender(``); const componentA = ngMocks.find(fixture.debugElement, AComponent); - expect(componentA.componentInstance).toEqual(jasmine.any(AComponent)); + expect(componentA.componentInstance).toEqual( + jasmine.any(AComponent), + ); - const componentB = ngMocks.find(fixture.debugElement, BComponent, null); + const componentB = ngMocks.find( + fixture.debugElement, + BComponent, + null, + ); expect(componentB).toBe(null); }); it('find selector: string', () => { const fixture = MockRender(``); - const componentB = ngMocks.find(fixture.debugElement, 'component-b'); - expect(componentB.componentInstance).toEqual(jasmine.any(BComponent)); + const componentB = ngMocks.find( + fixture.debugElement, + 'component-b', + ); + expect(componentB.componentInstance).toEqual( + jasmine.any(BComponent), + ); - const componentA = ngMocks.find(fixture.debugElement, 'component-a', null); + const componentA = ngMocks.find( + fixture.debugElement, + 'component-a', + null, + ); expect(componentA).toBe(null); }); it('find selector: missed string', () => { const fixture = MockRender(``); - expect(() => ngMocks.find(fixture.debugElement, 'component-a')).toThrowError(/Cannot find an element/); + expect(() => + ngMocks.find(fixture.debugElement, 'component-a'), + ).toThrowError(/Cannot find an element/); }); it('findAll selector: T', () => { - const fixture = MockRender(``); + const fixture = MockRender( + ``, + ); const componentA = ngMocks.findAll(fixture, AComponent); expect(componentA.length).toBe(2); - expect(componentA[0].componentInstance).toEqual(jasmine.any(AComponent)); - expect(componentA[1].componentInstance).toEqual(jasmine.any(AComponent)); + expect(componentA[0].componentInstance).toEqual( + jasmine.any(AComponent), + ); + expect(componentA[1].componentInstance).toEqual( + jasmine.any(AComponent), + ); - const componentB = ngMocks.findAll(fixture.debugElement, BComponent); + const componentB = ngMocks.findAll( + fixture.debugElement, + BComponent, + ); expect(componentB.length).toBe(0); }); it('findAll selector: string', () => { - const fixture = MockRender(``); + const fixture = MockRender( + ``, + ); const componentB = ngMocks.findAll(fixture, 'component-b'); expect(componentB.length).toEqual(2); - expect(componentB[0].componentInstance).toEqual(jasmine.any(BComponent)); - expect(componentB[0].componentInstance).toEqual(jasmine.any(BComponent)); + expect(componentB[0].componentInstance).toEqual( + jasmine.any(BComponent), + ); + expect(componentB[0].componentInstance).toEqual( + jasmine.any(BComponent), + ); - const componentA = ngMocks.findAll(fixture.debugElement, 'component-a'); + const componentA = ngMocks.findAll( + fixture.debugElement, + 'component-a', + ); expect(componentA.length).toBe(0); }); it('findInstance throws an error', () => { const fixture = MockRender(``); - expect(() => ngMocks.findInstance(fixture.debugElement, BComponent)).toThrowError( + expect(() => + ngMocks.findInstance(fixture.debugElement, BComponent), + ).toThrowError( /Cannot find an instance via ngMocks.findInstance\(BComponent\)/, ); }); it('findInstance returns default value', () => { const fixture = MockRender(``); - const instance = ngMocks.findInstance(fixture.debugElement, BComponent, undefined); + const instance = ngMocks.findInstance( + fixture.debugElement, + BComponent, + undefined, + ); expect(instance).toBeUndefined(); }); @@ -216,14 +291,19 @@ describe('MockHelper:getDirective', () => { it('input throws', () => { const fixture = MockRender(`
    `); const node = ngMocks.find(fixture.debugElement, 'div'); - expect(() => ngMocks.input(node, 'default')).toThrowError(/Cannot find default input/); + expect(() => ngMocks.input(node, 'default')).toThrowError( + /Cannot find default input/, + ); }); it('output returns emitter', () => { const spy = jasmine.createSpy('someOutput'); - const fixture = MockRender(`
    `, { - spy, - }); + const fixture = MockRender( + `
    `, + { + spy, + }, + ); const node = ngMocks.find(fixture.debugElement, 'div'); const output = ngMocks.output(node, 'someOutput'); @@ -233,9 +313,12 @@ describe('MockHelper:getDirective', () => { it('output returns default value', () => { const spy = jasmine.createSpy('someOutput'); - const fixture = MockRender(`
    `, { - spy, - }); + const fixture = MockRender( + `
    `, + { + spy, + }, + ); const node = ngMocks.find(fixture.debugElement, 'div'); const output = ngMocks.output(node, 'default', undefined); @@ -245,17 +328,25 @@ describe('MockHelper:getDirective', () => { it('output throws', () => { const fixture = MockRender(`
    `); const node = ngMocks.find(fixture.debugElement, 'div'); - expect(() => ngMocks.output(node, 'default')).toThrowError(/Cannot find default output/); + expect(() => ngMocks.output(node, 'default')).toThrowError( + /Cannot find default output/, + ); }); it('get returns default value', () => { const fixture = MockRender('
    '); - const actual = ngMocks.get(fixture.debugElement, ExampleDirective, undefined); + const actual = ngMocks.get( + fixture.debugElement, + ExampleDirective, + undefined, + ); expect(actual).toBeUndefined(); }); it('get throws an error', () => { const fixture = MockRender('
    '); - expect(() => ngMocks.get(fixture.debugElement, ExampleDirective)).toThrowError(/Cannot find ExampleDirective/); + expect(() => + ngMocks.get(fixture.debugElement, ExampleDirective), + ).toThrowError(/Cannot find ExampleDirective/); }); }); diff --git a/lib/mock-module/mock-module.spec.ts b/lib/mock-module/mock-module.spec.ts index d4110da1fc..afc39c93c3 100644 --- a/lib/mock-module/mock-module.spec.ts +++ b/lib/mock-module/mock-module.spec.ts @@ -11,7 +11,11 @@ import { Injector, NgModule, } from '@angular/core'; -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { + async, + ComponentFixture, + TestBed, +} from '@angular/core/testing'; import { BrowserModule, By } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; @@ -60,7 +64,10 @@ describe('MockModule', () => { beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ComponentSubject], - imports: [MockModule(ParentModule), MockModule(ModuleWithProvidersModule)], + imports: [ + MockModule(ParentModule), + MockModule(ModuleWithProvidersModule), + ], }) .compileComponents() .then(() => { @@ -70,8 +77,9 @@ describe('MockModule', () => { })); it('should do stuff', () => { - const mockComponent = fixture.debugElement.query(By.directive(MockComponent(ExampleComponent))) - .componentInstance as ExampleComponent; + const mockComponent = fixture.debugElement.query( + By.directive(MockComponent(ExampleComponent)), + ).componentInstance as ExampleComponent; expect(mockComponent).not.toBeNull(); }); }); @@ -82,7 +90,10 @@ describe('SameImportsModules', () => { beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [SameImportsComponent], - imports: [MockModule(SameImports1Module), MockModule(SameImports2Module)], + imports: [ + MockModule(SameImports1Module), + MockModule(SameImports2Module), + ], }) .compileComponents() .then(() => { @@ -92,7 +103,9 @@ describe('SameImportsModules', () => { })); it('should be imported correctly', () => { - expect(fixture.componentInstance).toEqual(jasmine.any(SameImportsComponent)); + expect(fixture.componentInstance).toEqual( + jasmine.any(SameImportsComponent), + ); expect(fixture.nativeElement.innerText).toEqual('same imports'); }); }); @@ -118,7 +131,9 @@ describe('NeverMockModules', () => { })); it('should not fail when we pass them to MockModule', () => { - expect(fixture.componentInstance).toEqual(jasmine.any(SameImportsComponent)); + expect(fixture.componentInstance).toEqual( + jasmine.any(SameImportsComponent), + ); expect(fixture.nativeElement.innerText).toEqual('same imports'); }); }); @@ -139,7 +154,9 @@ describe('RouterModule', () => { })); it('should not fail when we pass RouterModule to MockModule', () => { - expect(fixture.componentInstance).toEqual(jasmine.any(ExampleComponent)); + expect(fixture.componentInstance).toEqual( + jasmine.any(ExampleComponent), + ); expect(fixture.nativeElement.innerText).toEqual('My Example'); }); }); @@ -164,7 +181,9 @@ describe('Usage of cached nested module', () => { })); it('should be able to find component', () => { - expect(fixture.componentInstance).toEqual(jasmine.any(ExampleConsumerComponent)); + expect(fixture.componentInstance).toEqual( + jasmine.any(ExampleConsumerComponent), + ); }); }); @@ -182,7 +201,9 @@ describe('Usage of cached nested module', () => { })); it('should be able to find component', () => { - expect(fixture.componentInstance).toEqual(jasmine.any(ExampleConsumerComponent)); + expect(fixture.componentInstance).toEqual( + jasmine.any(ExampleConsumerComponent), + ); }); }); }); @@ -237,23 +258,33 @@ describe('mockProvider', () => { }); it('should return default value on primitives', () => { - expect(mockProvider({ provide: CUSTOM_TOKEN, useValue: undefined })).toEqual({ + expect( + mockProvider({ provide: CUSTOM_TOKEN, useValue: undefined }), + ).toEqual({ provide: CUSTOM_TOKEN, useValue: undefined, }); - expect(mockProvider({ provide: CUSTOM_TOKEN, useValue: 123 })).toEqual({ + expect( + mockProvider({ provide: CUSTOM_TOKEN, useValue: 123 }), + ).toEqual({ provide: CUSTOM_TOKEN, useValue: 0, }); - expect(mockProvider({ provide: CUSTOM_TOKEN, useValue: true })).toEqual({ + expect( + mockProvider({ provide: CUSTOM_TOKEN, useValue: true }), + ).toEqual({ provide: CUSTOM_TOKEN, useValue: false, }); - expect(mockProvider({ provide: CUSTOM_TOKEN, useValue: 'true' })).toEqual({ + expect( + mockProvider({ provide: CUSTOM_TOKEN, useValue: 'true' }), + ).toEqual({ provide: CUSTOM_TOKEN, useValue: '', }); - expect(mockProvider({ provide: CUSTOM_TOKEN, useValue: null })).toEqual({ + expect( + mockProvider({ provide: CUSTOM_TOKEN, useValue: null }), + ).toEqual({ provide: CUSTOM_TOKEN, useValue: null, }); diff --git a/lib/mock-pipe/mock-pipe.spec.ts b/lib/mock-pipe/mock-pipe.spec.ts index d3091acd7e..dd628ae87f 100644 --- a/lib/mock-pipe/mock-pipe.spec.ts +++ b/lib/mock-pipe/mock-pipe.spec.ts @@ -1,5 +1,9 @@ import { Component, Pipe, PipeTransform } from '@angular/core'; -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { + async, + ComponentFixture, + TestBed, +} from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { isMockedNgDefOf } from '../common/func.is-mocked-ng-def-of'; @@ -20,7 +24,9 @@ export class AnotherExamplePipe implements PipeTransform { selector: 'example-component', template: ` {{ someStuff | mockPipe: 'foo' }} - {{ someStuff | anotherMockPipe: 'fighters' }} + {{ + someStuff | anotherMockPipe: 'fighters' + }} `, }) export class ExampleComponent { @@ -34,7 +40,9 @@ describe('MockPipe', () => { const mocks = MockPipes(ExamplePipe, AnotherExamplePipe); expect(mocks.length).toEqual(2); expect(isMockedNgDefOf(mocks[0], ExamplePipe, 'p')).toBeTruthy(); - expect(isMockedNgDefOf(mocks[1], AnotherExamplePipe, 'p')).toBeTruthy(); + expect( + isMockedNgDefOf(mocks[1], AnotherExamplePipe, 'p'), + ).toBeTruthy(); }); it('used default transform', () => { @@ -46,7 +54,11 @@ describe('MockPipe', () => { describe('Base tests-jasmine', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - declarations: [ExampleComponent, MockPipe(ExamplePipe, () => 'foo'), MockPipe(AnotherExamplePipe)], + declarations: [ + ExampleComponent, + MockPipe(ExamplePipe, () => 'foo'), + MockPipe(AnotherExamplePipe), + ], }).compileComponents(); })); @@ -56,12 +68,18 @@ describe('MockPipe', () => { }); it('should not display the word hi that is printed by the pipe, because it is replaced with its mock copy', () => { - expect(fixture.debugElement.query(By.css('#anotherExamplePipe')).nativeElement.innerHTML).toEqual(''); + expect( + fixture.debugElement.query(By.css('#anotherExamplePipe')) + .nativeElement.innerHTML, + ).toEqual(''); }); describe('with transform override', () => { it('should return the result of the provided transform function', () => { - expect(fixture.debugElement.query(By.css('#examplePipe')).nativeElement.innerHTML).toEqual('foo'); + expect( + fixture.debugElement.query(By.css('#examplePipe')) + .nativeElement.innerHTML, + ).toEqual('foo'); }); }); }); @@ -69,7 +87,11 @@ describe('MockPipe', () => { describe('Cache check', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - declarations: [ExampleComponent, MockPipe(ExamplePipe, () => 'bar'), MockPipe(AnotherExamplePipe)], + declarations: [ + ExampleComponent, + MockPipe(ExamplePipe, () => 'bar'), + MockPipe(AnotherExamplePipe), + ], }).compileComponents(); })); @@ -79,7 +101,10 @@ describe('MockPipe', () => { }); it('should return the result of the new provided transform function', () => { - expect(fixture.debugElement.query(By.css('#examplePipe')).nativeElement.innerHTML).toEqual('bar'); + expect( + fixture.debugElement.query(By.css('#examplePipe')) + .nativeElement.innerHTML, + ).toEqual('bar'); }); it('returns cached version', () => { diff --git a/lib/mock-provider/mock-provider.spec.ts b/lib/mock-provider/mock-provider.spec.ts index 21009ad7bc..d50ae37160 100644 --- a/lib/mock-provider/mock-provider.spec.ts +++ b/lib/mock-provider/mock-provider.spec.ts @@ -49,6 +49,8 @@ describe('mock-provider', () => { provide: TargetService, useFactory: jasmine.anything(), }); - expect(actual[1].useFactory()).toEqual(jasmine.any(TargetService)); + expect(actual[1].useFactory()).toEqual( + jasmine.any(TargetService), + ); }); }); diff --git a/lib/mock-render/mock-render.spec.ts b/lib/mock-render/mock-render.spec.ts index 06b1bae489..5bf0ab254f 100644 --- a/lib/mock-render/mock-render.spec.ts +++ b/lib/mock-render/mock-render.spec.ts @@ -9,19 +9,33 @@ import { ngMocks } from '../mock-helper/mock-helper'; import { MockService } from '../mock-service/mock-service'; import { MockRender } from './mock-render'; -import { EmptyComponent, RenderRealComponent, WithoutSelectorComponent } from './mock-render.spec.fixtures'; -import { MockedComponentFixture, MockedDebugElement, MockedDebugNode } from './types'; +import { + EmptyComponent, + RenderRealComponent, + WithoutSelectorComponent, +} from './mock-render.spec.fixtures'; +import { + MockedComponentFixture, + MockedDebugElement, + MockedDebugNode, +} from './types'; describe('MockRender', () => { beforeEach(() => { TestBed.configureTestingModule({ - declarations: [RenderRealComponent, WithoutSelectorComponent, EmptyComponent], + declarations: [ + RenderRealComponent, + WithoutSelectorComponent, + EmptyComponent, + ], }); }); it('respects no inputs and outputs', () => { const fixture = MockRender(EmptyComponent); - expect(fixture.nativeElement.innerHTML).toEqual('empty'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'empty', + ); }); it('respects observables', () => { @@ -65,15 +79,21 @@ describe('MockRender', () => { expect(fixture).toBeTruthy(); // Asserting inputs. - expect(fixture.nativeElement.innerText.replace(/\s+/gim, ' ').trim()).toEqual(`before injected content after`); + expect( + fixture.nativeElement.innerText.replace(/\s+/gim, ' ').trim(), + ).toEqual(`before injected content after`); // Asserting dynamic changes on inputs. fixture.componentInstance.mockContent = 'dynamic content'; fixture.detectChanges(); - expect(fixture.nativeElement.innerText.replace(/\s+/gim, ' ').trim()).toEqual(`before dynamic content after`); + expect( + fixture.nativeElement.innerText.replace(/\s+/gim, ' ').trim(), + ).toEqual(`before dynamic content after`); // Asserting outputs. - const spanElement = fixture.debugElement.query(By.css('render-real-component span')); + const spanElement = fixture.debugElement.query( + By.css('render-real-component span'), + ); expect(spanElement).toBeTruthy(); spanElement.triggerEventHandler('click', assertPayload); expect(spy).toHaveBeenCalledWith(assertPayload); @@ -91,9 +111,13 @@ describe('MockRender', () => { }, false, ); - expect(fixture.debugElement.nativeElement.innerText).not.toContain('injected content'); + expect(fixture.nativeElement.innerText).not.toContain( + 'injected content', + ); fixture.detectChanges(); - expect(fixture.debugElement.nativeElement.innerText).toContain('injected content'); + expect(fixture.nativeElement.innerText).toContain( + 'injected content', + ); }); it('binds inputs and outputs with a provided component', () => { @@ -116,12 +140,16 @@ describe('MockRender', () => { ); // because template can include more than 1 component, be wrapped by any html element etc. expect(fixture.point).toBeDefined(); - expect(fixture.point.componentInstance).toEqual(jasmine.any(RenderRealComponent)); + expect(fixture.point.componentInstance).toEqual( + jasmine.any(RenderRealComponent), + ); }); it('returns pointer with a provided component', () => { const fixture = MockRender(RenderRealComponent); - expect(fixture.point.componentInstance).toEqual(jasmine.any(RenderRealComponent)); + expect(fixture.point.componentInstance).toEqual( + jasmine.any(RenderRealComponent), + ); }); it('returns pointer with a provided component', () => { @@ -144,7 +172,7 @@ describe('MockRender', () => { it('does not render a component without selector', () => { const fixture = MockRender(WithoutSelectorComponent); - expect(fixture.debugElement.nativeElement.innerHTML).toEqual(''); + expect(fixture.nativeElement.innerHTML).toEqual(''); }); it('assigns outputs to a literals', () => { @@ -155,7 +183,9 @@ describe('MockRender', () => { const expected = { value: Math.random(), }; - ngMocks.find(fixture.debugElement, 'span').triggerEventHandler('click', expected); + ngMocks + .find(fixture.debugElement, 'span') + .triggerEventHandler('click', expected); expect(fixture.componentInstance.click as any).toEqual(expected); }); @@ -168,8 +198,12 @@ describe('MockRender', () => { value: Math.random(), }; let actual: any; - fixture.componentInstance.click.pipe(first()).subscribe(value => (actual = value)); - ngMocks.find(fixture.debugElement, 'span').triggerEventHandler('click', expected); + fixture.componentInstance.click + .pipe(first()) + .subscribe(value => (actual = value)); + ngMocks + .find(fixture.debugElement, 'span') + .triggerEventHandler('click', expected); expect(actual).toEqual(expected); }); diff --git a/lib/mock-service/mock-service.spec.ts b/lib/mock-service/mock-service.spec.ts index 92d6dc5af1..6f4e546c68 100644 --- a/lib/mock-service/mock-service.spec.ts +++ b/lib/mock-service/mock-service.spec.ts @@ -1,11 +1,17 @@ // tslint:disable max-file-line-count -import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; +import { + HttpClientModule, + HTTP_INTERCEPTORS, +} from '@angular/common/http'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { InjectionToken, NgModule } from '@angular/core'; import { TestBed } from '@angular/core/testing'; -import { NG_MOCKS_GUARDS, NG_MOCKS_INTERCEPTORS } from '../common/core.tokens'; +import { + NG_MOCKS_GUARDS, + NG_MOCKS_INTERCEPTORS, +} from '../common/core.tokens'; import ngMocksUniverse from '../common/ng-mocks-universe'; import { MockBuilder } from '../mock-builder/mock-builder'; import { ngMocks } from '../mock-helper/mock-helper'; @@ -105,12 +111,21 @@ describe('MockService', () => { expect(mockService).toEqual(jasmine.any(Object)); // all properties should be undefined, maybe defined as getters and setters. - expect(mockService.deepParentMethodName).toBeUndefined('deepParentMethodName'); + expect(mockService.deepParentMethodName).toBeUndefined( + 'deepParentMethodName', + ); // all methods should be defined as functions which return undefined. - expect(mockService.deepParentMethod).toEqual(jasmine.any(Function), 'deepParentMethod'); - expect(mockService.deepParentMethod()).toBeUndefined('deepParentMethod()'); - expect(ngMocks.stub(mockService, 'deepParentMethod').and.identity).toBe('DeepParentClass.deepParentMethod'); + expect(mockService.deepParentMethod).toEqual( + jasmine.any(Function), + 'deepParentMethod', + ); + expect(mockService.deepParentMethod()).toBeUndefined( + 'deepParentMethod()', + ); + expect( + ngMocks.stub(mockService, 'deepParentMethod').and.identity, + ).toBe('DeepParentClass.deepParentMethod'); }); it('should mock own and parent methods of a class', () => { @@ -118,24 +133,56 @@ describe('MockService', () => { expect(mockService).toEqual(jasmine.any(ChildClass)); // all properties should be undefined, maybe defined as getters and setters. - expect(mockService.deepParentMethodName).toBeUndefined('deepParentMethodName'); - expect(mockService.parentMethodName).toBeUndefined('parentMethodName'); - expect(mockService.overrideMeName).toBeUndefined('overrideMeName'); - expect(mockService.childMethodName).toBeUndefined('childMethodName'); + expect(mockService.deepParentMethodName).toBeUndefined( + 'deepParentMethodName', + ); + expect(mockService.parentMethodName).toBeUndefined( + 'parentMethodName', + ); + expect(mockService.overrideMeName).toBeUndefined( + 'overrideMeName', + ); + expect(mockService.childMethodName).toBeUndefined( + 'childMethodName', + ); // all methods should be defined as functions which return undefined. - expect(mockService.deepParentMethod).toEqual(jasmine.any(Function), 'deepParentMethod'); - expect(mockService.deepParentMethod()).toBeUndefined('deepParentMethod()'); - expect(ngMocks.stub(mockService, 'deepParentMethod').and.identity).toBe('ChildClass.deepParentMethod'); - expect(mockService.parentMethod).toEqual(jasmine.any(Function), 'parentMethod'); - expect(mockService.parentMethod()).toBeUndefined('parentMethod()'); - expect(ngMocks.stub(mockService, 'parentMethod').and.identity).toBe('ChildClass.parentMethod'); - expect(mockService.overrideMe).toEqual(jasmine.any(Function), 'overrideMe'); + expect(mockService.deepParentMethod).toEqual( + jasmine.any(Function), + 'deepParentMethod', + ); + expect(mockService.deepParentMethod()).toBeUndefined( + 'deepParentMethod()', + ); + expect( + ngMocks.stub(mockService, 'deepParentMethod').and.identity, + ).toBe('ChildClass.deepParentMethod'); + expect(mockService.parentMethod).toEqual( + jasmine.any(Function), + 'parentMethod', + ); + expect(mockService.parentMethod()).toBeUndefined( + 'parentMethod()', + ); + expect( + ngMocks.stub(mockService, 'parentMethod').and.identity, + ).toBe('ChildClass.parentMethod'); + expect(mockService.overrideMe).toEqual( + jasmine.any(Function), + 'overrideMe', + ); expect(mockService.overrideMe()).toBeUndefined('overrideMe()'); - expect(ngMocks.stub(mockService, 'overrideMe').and.identity).toBe('ChildClass.overrideMe'); - expect(mockService.childMethod).toEqual(jasmine.any(Function), 'childMethod'); + expect( + ngMocks.stub(mockService, 'overrideMe').and.identity, + ).toBe('ChildClass.overrideMe'); + expect(mockService.childMethod).toEqual( + jasmine.any(Function), + 'childMethod', + ); expect(mockService.childMethod()).toBeUndefined('childMethod()'); - expect(ngMocks.stub(mockService, 'childMethod').and.identity).toBe('ChildClass.childMethod'); + expect( + ngMocks.stub(mockService, 'childMethod').and.identity, + ).toBe('ChildClass.childMethod'); }); it('should mock an instance of a class as an object', () => { @@ -143,24 +190,56 @@ describe('MockService', () => { expect(mockService).toEqual(jasmine.any(ChildClass)); // all properties should be undefined, maybe defined as getters and setters. - expect(mockService.deepParentMethodName).toBeUndefined('deepParentMethodName'); - expect(mockService.parentMethodName).toBeUndefined('parentMethodName'); - expect(mockService.overrideMeName).toBeUndefined('overrideMeName'); - expect(mockService.childMethodName).toBeUndefined('childMethodName'); + expect(mockService.deepParentMethodName).toBeUndefined( + 'deepParentMethodName', + ); + expect(mockService.parentMethodName).toBeUndefined( + 'parentMethodName', + ); + expect(mockService.overrideMeName).toBeUndefined( + 'overrideMeName', + ); + expect(mockService.childMethodName).toBeUndefined( + 'childMethodName', + ); // all methods should be defined as functions which return undefined. - expect(mockService.deepParentMethod).toEqual(jasmine.any(Function), 'deepParentMethod'); - expect(mockService.deepParentMethod()).toBeUndefined('deepParentMethod()'); - expect(mockService.deepParentMethod.and.identity).toBe('ChildClass.deepParentMethod'); - expect(mockService.parentMethod).toEqual(jasmine.any(Function), 'parentMethod'); - expect(mockService.parentMethod()).toBeUndefined('parentMethod()'); - expect(mockService.parentMethod.and.identity).toBe('ChildClass.parentMethod'); - expect(mockService.overrideMe).toEqual(jasmine.any(Function), 'overrideMe'); + expect(mockService.deepParentMethod).toEqual( + jasmine.any(Function), + 'deepParentMethod', + ); + expect(mockService.deepParentMethod()).toBeUndefined( + 'deepParentMethod()', + ); + expect(mockService.deepParentMethod.and.identity).toBe( + 'ChildClass.deepParentMethod', + ); + expect(mockService.parentMethod).toEqual( + jasmine.any(Function), + 'parentMethod', + ); + expect(mockService.parentMethod()).toBeUndefined( + 'parentMethod()', + ); + expect(mockService.parentMethod.and.identity).toBe( + 'ChildClass.parentMethod', + ); + expect(mockService.overrideMe).toEqual( + jasmine.any(Function), + 'overrideMe', + ); expect(mockService.overrideMe()).toBeUndefined('overrideMe()'); - expect(mockService.overrideMe.and.identity).toBe('ChildClass.overrideMe'); - expect(mockService.childMethod).toEqual(jasmine.any(Function), 'childMethod'); + expect(mockService.overrideMe.and.identity).toBe( + 'ChildClass.overrideMe', + ); + expect(mockService.childMethod).toEqual( + jasmine.any(Function), + 'childMethod', + ); expect(mockService.childMethod()).toBeUndefined('childMethod()'); - expect(mockService.childMethod.and.identity).toBe('ChildClass.childMethod'); + expect(mockService.childMethod.and.identity).toBe( + 'ChildClass.childMethod', + ); }); it('should mock own and nested properties of an object', () => { @@ -194,16 +273,26 @@ describe('MockService', () => { func3: jasmine.any(Function), }); - expect(mockService.child1.child11.func1()).toBeUndefined('func1()'); - expect(mockService.child1.child11.func1.and.identity).toBe('func:instance.child1.child11.func1'); + expect(mockService.child1.child11.func1()).toBeUndefined( + 'func1()', + ); + expect(mockService.child1.child11.func1.and.identity).toBe( + 'func:instance.child1.child11.func1', + ); expect(mockService.func2()).toBeUndefined('func2()'); - expect(mockService.func2.and.identity).toBe('func:instance.func2'); + expect(mockService.func2.and.identity).toBe( + 'func:instance.func2', + ); expect(mockService.func3()).toBeUndefined('func3()'); - expect(mockService.func3.and.identity).toBe('func:instance.func3'); + expect(mockService.func3.and.identity).toBe( + 'func:instance.func3', + ); }); it('mocks getters, setters and methods in a way that jasmine can mock them w/o an issue', () => { - const mock: GetterSetterMethodHuetod = MockService(GetterSetterMethodHuetod); + const mock: GetterSetterMethodHuetod = MockService( + GetterSetterMethodHuetod, + ); expect(mock).toBeDefined(); // Creating a mock on the getter. @@ -215,14 +304,18 @@ describe('MockService', () => { // Creating a mock on the setter. spyOnProperty(mock, 'name', 'set'); mock.name = 'mock'; - expect(ngMocks.stub(mock, 'name', 'set')).toHaveBeenCalledWith('mock'); + expect(ngMocks.stub(mock, 'name', 'set')).toHaveBeenCalledWith( + 'mock', + ); // Creating a mock on the method. spyOn(mock, 'nameMethod').and.returnValue('mock'); // for jest // spyOn(mock, 'nameMethod').mockReturnValue('mock'); expect(mock.nameMethod('mock')).toEqual('mock'); - expect(ngMocks.stub(mock, 'nameMethod')).toHaveBeenCalledWith('mock'); + expect(ngMocks.stub(mock, 'nameMethod')).toHaveBeenCalledWith( + 'mock', + ); }); it('mocks injection tokens as undefined', () => { @@ -305,15 +398,25 @@ describe('replaceWithMocks', () => { providers: [ { provide: 'test', - useValue: [DeepParentClass, ParentClass, GetterSetterMethodHuetod], + useValue: [ + DeepParentClass, + ParentClass, + GetterSetterMethodHuetod, + ], }, ], }) class TargetModule {} - await MockBuilder().mock(TargetModule).keep('test').exclude(ParentClass); + await MockBuilder() + .mock(TargetModule) + .keep('test') + .exclude(ParentClass); const actual = TestBed.get('test'); - expect(actual).toEqual([DeepParentClass, GetterSetterMethodHuetod]); + expect(actual).toEqual([ + DeepParentClass, + GetterSetterMethodHuetod, + ]); }); it('removes excluded things from an object', async () => { @@ -331,7 +434,10 @@ describe('replaceWithMocks', () => { }) class TargetModule {} - await MockBuilder().mock(TargetModule).keep('test').exclude(ParentClass); + await MockBuilder() + .mock(TargetModule) + .keep('test') + .exclude(ParentClass); const actual = TestBed.get('test'); expect(actual).toEqual({ DeepParentClass, @@ -345,7 +451,11 @@ describe('replaceWithMocks', () => { { provide: 'test', useValue: { - canActivate: [DeepParentClass, GetterSetterMethodHuetod, ParentClass], + canActivate: [ + DeepParentClass, + GetterSetterMethodHuetod, + ParentClass, + ], }, }, ], @@ -355,7 +465,11 @@ describe('replaceWithMocks', () => { await MockBuilder().mock(TargetModule).keep('test'); const actual = TestBed.get('test'); expect(actual).toEqual({ - canActivate: [DeepParentClass, GetterSetterMethodHuetod, ParentClass], + canActivate: [ + DeepParentClass, + GetterSetterMethodHuetod, + ParentClass, + ], }); }); @@ -365,14 +479,21 @@ describe('replaceWithMocks', () => { { provide: 'test', useValue: { - canActivate: [DeepParentClass, GetterSetterMethodHuetod, ParentClass], + canActivate: [ + DeepParentClass, + GetterSetterMethodHuetod, + ParentClass, + ], }, }, ], }) class TargetModule {} - await MockBuilder().mock(TargetModule).keep('test').exclude(NG_MOCKS_GUARDS); + await MockBuilder() + .mock(TargetModule) + .keep('test') + .exclude(NG_MOCKS_GUARDS); const actual = TestBed.get('test'); expect(actual).toEqual({ canActivate: [], @@ -405,6 +526,8 @@ describe('resolveProvider', () => { .keep(HTTP_INTERCEPTORS) .exclude(NG_MOCKS_INTERCEPTORS); const actual = TestBed.get(HTTP_INTERCEPTORS); - expect(actual).not.toEqual(jasmine.arrayContaining([false, true])); + expect(actual).not.toEqual( + jasmine.arrayContaining([false, true]), + ); }); }); diff --git a/package.release.json b/package.release.json index 3795e521aa..aa0dfcad2c 100644 --- a/package.release.json +++ b/package.release.json @@ -1,23 +1,23 @@ { "name": "ng-mocks", "version": "0.0.0", - "description": "A library for creating angular 5+ mock components, directives, pipes, services, providers and modules in unit tests, which also includes shallow rendering and precise stubs to dump child dependencies.", + "description": "An Angular 5+ library for creating mock components, directives, pipes, services, providers and modules in unit tests, which also includes shallow rendering and precise stubs to dump child dependencies.", "keywords": [ - "angular unit tests", - "angular testing", - "mock component", - "mock directive", - "mock pipe", - "mock provider", - "mock service", - "shallow render", - "shallow rendering", - "an angular test example", - "mocking TestBed how to", - "stub child dependency", - "stubbing", - "dumb", - "create mock dummy child copies" + "angular", + "test", + "testing", + "mock", + "mocking", + "component", + "directive", + "pipe", + "provider", + "service", + "TestBed", + "how-to", + "frontend", + "front-end", + "create a stub-dummy child dependency via stubbing dumb enzyme-render" ], "author": { "name": "Isaac Datlof", diff --git a/tests/NG_MOCKS_ROOT_PROVIDERS/test.spec.ts b/tests/NG_MOCKS_ROOT_PROVIDERS/test.spec.ts index 74d1eb7905..8a1377dfd6 100644 --- a/tests/NG_MOCKS_ROOT_PROVIDERS/test.spec.ts +++ b/tests/NG_MOCKS_ROOT_PROVIDERS/test.spec.ts @@ -1,5 +1,14 @@ -import { Component, Injectable as InjectableSource, NgModule, VERSION } from '@angular/core'; -import { MockBuilder, MockRender, NG_MOCKS_ROOT_PROVIDERS } from 'ng-mocks'; +import { + Component, + Injectable as InjectableSource, + NgModule, + VERSION, +} from '@angular/core'; +import { + MockBuilder, + MockRender, + NG_MOCKS_ROOT_PROVIDERS, +} from 'ng-mocks'; // Because of A5 we need to cast Injectable to any type. // But because of A10+ we need to do it via a middle function. @@ -63,20 +72,32 @@ describe('NG_MOCKS_ROOT_PROVIDERS', () => { }); describe('default for a kept module', () => { - beforeEach(() => MockBuilder(Target1Component, CombinedModule).keep(Target1Module)); + beforeEach(() => + MockBuilder(Target1Component, CombinedModule).keep( + Target1Module, + ), + ); it('keeps its global service', () => { const fixture = MockRender(Target1Component); - expect(fixture.nativeElement.innerHTML).toEqual('target-1'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'target-1', + ); }); }); describe('mock the token', () => { - beforeEach(() => MockBuilder(Target1Component, CombinedModule).keep(Target1Module).mock(NG_MOCKS_ROOT_PROVIDERS)); + beforeEach(() => + MockBuilder(Target1Component, CombinedModule) + .keep(Target1Module) + .mock(NG_MOCKS_ROOT_PROVIDERS), + ); it('mocks global service for a kept module', () => { const fixture = MockRender(Target1Component); - expect(fixture.nativeElement.innerHTML).toEqual(''); + expect(fixture.nativeElement.innerHTML).toEqual( + '', + ); }); }); @@ -85,16 +106,24 @@ describe('NG_MOCKS_ROOT_PROVIDERS', () => { it('mocks its global service', () => { const fixture = MockRender(Target1Component); - expect(fixture.nativeElement.innerHTML).toEqual(''); + expect(fixture.nativeElement.innerHTML).toEqual( + '', + ); }); }); describe('keep the token', () => { - beforeEach(() => MockBuilder(Target1Component, CombinedModule).keep(NG_MOCKS_ROOT_PROVIDERS)); + beforeEach(() => + MockBuilder(Target1Component, CombinedModule).keep( + NG_MOCKS_ROOT_PROVIDERS, + ), + ); it('keeps global service for a mock module', () => { const fixture = MockRender(Target1Component); - expect(fixture.nativeElement.innerHTML).toEqual('target-1'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'target-1', + ); }); }); }); diff --git a/tests/context-with-directives/context-with-directives.spec.ts b/tests/context-with-directives/context-with-directives.spec.ts index e9ca1f93e0..1469753fe4 100644 --- a/tests/context-with-directives/context-with-directives.spec.ts +++ b/tests/context-with-directives/context-with-directives.spec.ts @@ -5,7 +5,12 @@ import { CustomRootComponent } from './custom-root.component'; import { CustomTypeDirective } from './custom-type.directive'; describe('context-with-directives:real', () => { - beforeEach(() => MockBuilder().keep(CustomTypeDirective).keep(CustomRootComponent).keep(CommonModule)); + beforeEach(() => + MockBuilder() + .keep(CustomTypeDirective) + .keep(CustomRootComponent) + .keep(CommonModule), + ); it('renders everything right', () => { const fixture = MockRender(` @@ -31,36 +36,50 @@ describe('context-with-directives:real', () => { `); // template should be rendered under .template - expect(ngMocks.find(fixture.debugElement, '.template').nativeElement.innerHTML.replace(/\s+/gm, ' ')).toContain( - ' template w/ directive w/o binding ', - ); + expect( + ngMocks + .find(fixture.debugElement, '.template') + .nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toContain(' template w/ directive w/o binding '); // template1 should be rendered under .template1 - expect(ngMocks.find(fixture.debugElement, '.template1').nativeElement.innerHTML.replace(/\s+/gm, ' ')).toContain( - ' template w/ directive w/ binding 1 ', - ); + expect( + ngMocks + .find(fixture.debugElement, '.template1') + .nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toContain(' template w/ directive w/ binding 1 '); // template2 should not be rendered - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).not.toContain( - ' template w/ directive w/ binding w/o render ', - ); + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).not.toContain(' template w/ directive w/ binding w/o render '); // unused ng-templates shouldn't be rendered at all - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).not.toContain(' template w/o directive w/o binding '); - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).not.toContain(' template w/o directive w/ binding '); + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).not.toContain(' template w/o directive w/o binding '); + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).not.toContain(' template w/o directive w/ binding '); // ng-content contains header and footer - expect(ngMocks.find(fixture.debugElement, '.nested').nativeElement.innerHTML.replace(/\s+/, ' ')).toContain( - '
    header
    ', - ); - expect(ngMocks.find(fixture.debugElement, '.nested').nativeElement.innerHTML.replace(/\s+/, ' ')).toContain( - '
    footer
    ', - ); + expect( + ngMocks + .find(fixture.debugElement, '.nested') + .nativeElement.innerHTML.replace(/\s+/, ' '), + ).toContain('
    header
    '); + expect( + ngMocks + .find(fixture.debugElement, '.nested') + .nativeElement.innerHTML.replace(/\s+/, ' '), + ).toContain('
    footer
    '); }); }); describe('context-with-directives:mock', () => { - beforeEach(() => MockBuilder().mock(CustomTypeDirective).mock(CustomRootComponent)); + beforeEach(() => + MockBuilder().mock(CustomTypeDirective).mock(CustomRootComponent), + ); it('renders everything what is not template', () => { const fixture = MockRender(` @@ -85,12 +104,18 @@ describe('context-with-directives:mock', () => { `); - expect(fixture.nativeElement.innerHTML).toContain('
    header
    '); - expect(fixture.nativeElement.innerHTML).toContain('
    footer
    '); + expect(fixture.nativeElement.innerHTML).toContain( + '
    header
    ', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '
    footer
    ', + ); // No templates should be rendered when we mock them. // The reason for that is that only directive knows when to render it, that means if we want to render, // we should do that manually. - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).not.toContain(' template '); + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).not.toContain(' template '); }); }); diff --git a/tests/control-value-accessor-form-control/test.spec.ts b/tests/control-value-accessor-form-control/test.spec.ts index 7547c4279f..78321a9bd6 100644 --- a/tests/control-value-accessor-form-control/test.spec.ts +++ b/tests/control-value-accessor-form-control/test.spec.ts @@ -1,7 +1,16 @@ import { ReactiveFormsModule } from '@angular/forms'; -import { MockBuilder, MockComponent, MockRender, ngMocks } from 'ng-mocks'; - -import { ControlComponent, TargetComponent, TargetModule } from './fixtures'; +import { + MockBuilder, + MockComponent, + MockRender, + ngMocks, +} from 'ng-mocks'; + +import { + ControlComponent, + TargetComponent, + TargetModule, +} from './fixtures'; // a real case to check possible behavior. describe('control-value-accessor-form-control:real', () => { @@ -9,31 +18,42 @@ describe('control-value-accessor-form-control:real', () => { it('respects our formControl', () => { const fixture = MockRender(TargetComponent, {}, false); - const mock = ngMocks.find(fixture.debugElement, ControlComponent).componentInstance; + const mock = ngMocks.find(fixture.debugElement, ControlComponent) + .componentInstance; spyOn(mock, 'writeValue').and.callThrough(); spyOn(mock, 'setDisabledState').and.callThrough(); fixture.detectChanges(); expect(mock.writeValue).toHaveBeenCalledWith(null); expect(mock.setDisabledState).not.toHaveBeenCalled(); - expect(fixture.point.componentInstance.control.touched).toBeFalsy(); + expect( + fixture.point.componentInstance.control.touched, + ).toBeFalsy(); // checking via original component fixture.point.componentInstance.control.setValue('test1'); expect(mock.writeValue).toHaveBeenCalledWith('test1'); - expect(fixture.point.componentInstance.control.touched).toBeFalsy(); + expect( + fixture.point.componentInstance.control.touched, + ).toBeFalsy(); fixture.point.componentInstance.control.setValue('test2'); expect(mock.writeValue).toHaveBeenCalledWith('test2'); - expect(fixture.point.componentInstance.control.touched).toBeFalsy(); + expect( + fixture.point.componentInstance.control.touched, + ).toBeFalsy(); // checking that touch works mock.changeTouch(); - expect(fixture.point.componentInstance.control.touched).toBeTruthy(); + expect( + fixture.point.componentInstance.control.touched, + ).toBeTruthy(); // checking that reset works fixture.point.componentInstance.control.markAsUntouched(); - expect(fixture.point.componentInstance.control.touched).toBeFalsy(); + expect( + fixture.point.componentInstance.control.touched, + ).toBeFalsy(); // checking that disabled works fixture.point.componentInstance.control.disable(); @@ -45,18 +65,29 @@ describe('control-value-accessor-form-control:real', () => { // It only updates the original control's value. mock.changeValue('test3'); expect(mock.writeValue).not.toHaveBeenCalledWith('test3'); - expect(fixture.point.componentInstance.control.touched).toBeFalsy(); - expect(fixture.point.componentInstance.control.value).toBe('test3'); + expect( + fixture.point.componentInstance.control.touched, + ).toBeFalsy(); + expect(fixture.point.componentInstance.control.value).toBe( + 'test3', + ); }); }); // a way that ensures that a mock component behaves the same way as real one. describe('control-value-accessor-form-control:mock', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(ReactiveFormsModule)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule).keep( + ReactiveFormsModule, + ), + ); it('respects our formControl', () => { const fixture = MockRender(TargetComponent, {}, false); - const mock = ngMocks.find(fixture.debugElement, MockComponent(ControlComponent)).componentInstance; + const mock = ngMocks.find( + fixture.debugElement, + MockComponent(ControlComponent), + ).componentInstance; spyOn(mock, 'writeValue').and.callThrough(); spyOn(mock, 'setDisabledState').and.callThrough(); spyOn(mock, 'registerOnChange').and.callThrough(); @@ -65,25 +96,40 @@ describe('control-value-accessor-form-control:mock', () => { expect(mock.writeValue).toHaveBeenCalledWith(null); expect(mock.setDisabledState).not.toHaveBeenCalled(); - expect(fixture.point.componentInstance.control.touched).toBeFalsy(); + expect( + fixture.point.componentInstance.control.touched, + ).toBeFalsy(); // checking via original component fixture.point.componentInstance.control.setValue('test1'); expect(mock.writeValue).toHaveBeenCalledWith('test1'); - expect(fixture.point.componentInstance.control.touched).toBeFalsy(); + expect( + fixture.point.componentInstance.control.touched, + ).toBeFalsy(); fixture.point.componentInstance.control.setValue('test2'); expect(mock.writeValue).toHaveBeenCalledWith('test2'); - expect(fixture.point.componentInstance.control.touched).toBeFalsy(); + expect( + fixture.point.componentInstance.control.touched, + ).toBeFalsy(); // checking that touch works mock.__simulateTouch(); - expect(fixture.point.componentInstance.control.touched).toBeTruthy(); + expect( + fixture.point.componentInstance.control.touched, + ).toBeTruthy(); fixture.point.componentInstance.control.markAsUntouched(); - expect(fixture.point.componentInstance.control.touched).toBeFalsy(); + expect( + fixture.point.componentInstance.control.touched, + ).toBeFalsy(); // a way through a spy - ngMocks.stub(mock, 'registerOnTouched').calls.first().args[0](); - expect(fixture.point.componentInstance.control.touched).toBeTruthy(); + ngMocks + .stub(mock, 'registerOnTouched') + .calls.first() + .args[0](); + expect( + fixture.point.componentInstance.control.touched, + ).toBeTruthy(); fixture.point.componentInstance.control.markAsUntouched(); // checking that disabled works @@ -96,12 +142,23 @@ describe('control-value-accessor-form-control:mock', () => { // It only updates the original control's value. mock.__simulateChange('test3'); expect(mock.writeValue).not.toHaveBeenCalledWith('test3'); - expect(fixture.point.componentInstance.control.touched).toBeFalsy(); - expect(fixture.point.componentInstance.control.value).toBe('test3'); + expect( + fixture.point.componentInstance.control.touched, + ).toBeFalsy(); + expect(fixture.point.componentInstance.control.value).toBe( + 'test3', + ); // a way through a spy - ngMocks.stub(mock, 'registerOnChange').calls.first().args[0]('test4'); + ngMocks + .stub(mock, 'registerOnChange') + .calls.first() + .args[0]('test4'); expect(mock.writeValue).not.toHaveBeenCalledWith('test4'); - expect(fixture.point.componentInstance.control.touched).toBeFalsy(); - expect(fixture.point.componentInstance.control.value).toBe('test4'); + expect( + fixture.point.componentInstance.control.touched, + ).toBeFalsy(); + expect(fixture.point.componentInstance.control.value).toBe( + 'test4', + ); }); }); diff --git a/tests/control-value-accessor-ng-model/test.spec.ts b/tests/control-value-accessor-ng-model/test.spec.ts index 84f4f12a7d..6f07dc29f9 100644 --- a/tests/control-value-accessor-ng-model/test.spec.ts +++ b/tests/control-value-accessor-ng-model/test.spec.ts @@ -1,7 +1,16 @@ import { FormsModule, NgModel } from '@angular/forms'; -import { MockBuilder, MockComponent, MockRender, ngMocks } from 'ng-mocks'; - -import { ControlComponent, TargetComponent, TargetModule } from './fixtures'; +import { + MockBuilder, + MockComponent, + MockRender, + ngMocks, +} from 'ng-mocks'; + +import { + ControlComponent, + TargetComponent, + TargetModule, +} from './fixtures'; // a real case to check possible behavior. describe('control-value-accessor-ng-model:real', () => { @@ -9,7 +18,10 @@ describe('control-value-accessor-ng-model:real', () => { it('respects our ngModel', async () => { const fixture = MockRender(TargetComponent, {}, false); - const mockElement = ngMocks.find(fixture.debugElement, ControlComponent); + const mockElement = ngMocks.find( + fixture.debugElement, + ControlComponent, + ); const mock = mockElement.componentInstance; spyOn(mock, 'writeValue').and.callThrough(); spyOn(mock, 'setDisabledState').and.callThrough(); @@ -63,11 +75,16 @@ describe('control-value-accessor-ng-model:real', () => { // a way that ensures that a mock component behaves the same way as real one. describe('control-value-accessor-ng-model:mock', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(FormsModule)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule).keep(FormsModule), + ); it('respects our ngModel', async () => { const fixture = MockRender(TargetComponent, {}, false); - const mockElement = ngMocks.find(fixture.debugElement, MockComponent(ControlComponent)); + const mockElement = ngMocks.find( + fixture.debugElement, + MockComponent(ControlComponent), + ); const mock = mockElement.componentInstance; spyOn(mock, 'writeValue').and.callThrough(); spyOn(mock, 'setDisabledState').and.callThrough(); @@ -100,7 +117,10 @@ describe('control-value-accessor-ng-model:mock', () => { ngModel.control.markAsUntouched(); expect(ngModel.touched).toBeFalsy(); // a way through a spy - ngMocks.stub(mock, 'registerOnTouched').calls.first().args[0](); + ngMocks + .stub(mock, 'registerOnTouched') + .calls.first() + .args[0](); expect(ngModel.touched).toBeTruthy(); ngModel.control.markAsUntouched(); @@ -121,7 +141,10 @@ describe('control-value-accessor-ng-model:mock', () => { expect(ngModel.touched).toBeFalsy(); expect(fixture.point.componentInstance.value).toBe('test3'); // a way through a spy - ngMocks.stub(mock, 'registerOnChange').calls.first().args[0]('test4'); + ngMocks + .stub(mock, 'registerOnChange') + .calls.first() + .args[0]('test4'); expect(mock.writeValue).not.toHaveBeenCalledWith('test4'); expect(ngModel.touched).toBeFalsy(); expect(ngModel.value).toBe('test4'); diff --git a/tests/correct-module-exports-11/test.spec.ts b/tests/correct-module-exports-11/test.spec.ts index 4690d96e69..de757ac762 100644 --- a/tests/correct-module-exports-11/test.spec.ts +++ b/tests/correct-module-exports-11/test.spec.ts @@ -2,7 +2,12 @@ import { Component, NgModule } from '@angular/core'; import { TestBed } from '@angular/core/testing'; -import { MockBuilder, MockModule, MockRender, ngMocks } from 'ng-mocks'; +import { + MockBuilder, + MockModule, + MockRender, + ngMocks, +} from 'ng-mocks'; @Component({ selector: 'internal', @@ -47,21 +52,31 @@ describe('correct-module-exports-11:proper', () => { ); it('fails on not exported module', () => { - expect(() => MockRender(InternalComponent)).toThrowError(/'internal' is not a known element/); + expect(() => MockRender(InternalComponent)).toThrowError( + /'internal' is not a known element/, + ); }); it('renders an exported module', () => { const fixture = MockRender(ExternalComponent); - expect(fixture.nativeElement.innerHTML).toEqual(''); + expect(fixture.nativeElement.innerHTML).toEqual( + '', + ); }); }); describe('correct-module-exports-11:guts', () => { - beforeEach(() => TestBed.configureTestingModule(ngMocks.guts(null, TargetModule)).compileComponents()); + beforeEach(() => + TestBed.configureTestingModule( + ngMocks.guts(null, TargetModule), + ).compileComponents(), + ); it('renders an internal module', () => { const fixture = MockRender(InternalComponent); - expect(fixture.nativeElement.innerHTML).toEqual(''); + expect(fixture.nativeElement.innerHTML).toEqual( + '', + ); }); }); @@ -70,6 +85,8 @@ describe('correct-module-exports-11:builder', () => { it('renders an internal module', () => { const fixture = MockRender(InternalComponent); - expect(fixture.nativeElement.innerHTML).toEqual(''); + expect(fixture.nativeElement.innerHTML).toEqual( + '', + ); }); }); diff --git a/tests/double-decorator/example-1.spec.ts b/tests/double-decorator/example-1.spec.ts index 7a71d03b12..32d34fac70 100644 --- a/tests/double-decorator/example-1.spec.ts +++ b/tests/double-decorator/example-1.spec.ts @@ -1,4 +1,9 @@ -import { Component, Directive as DirectiveSource, Injectable, NgModule } from '@angular/core'; +import { + Component, + Directive as DirectiveSource, + Injectable, + NgModule, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { MockBuilder, MockRender } from 'ng-mocks'; @@ -54,12 +59,19 @@ describe('double-decorator:example-1', () => { name: 'mock', }); - beforeEach(() => MockBuilder(TargetComponent, TargetModule).mock(TargetProvider, myProviderMock())); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule).mock( + TargetProvider, + myProviderMock(), + ), + ); it('provides correct decoration of the directive', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toEqual('mock'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'mock', + ); }); }); }); diff --git a/tests/double-decorator/example-2.spec.ts b/tests/double-decorator/example-2.spec.ts index 695b8177c1..9324d0e458 100644 --- a/tests/double-decorator/example-2.spec.ts +++ b/tests/double-decorator/example-2.spec.ts @@ -1,4 +1,9 @@ -import { Component, Directive as DirectiveSource, Injectable, NgModule } from '@angular/core'; +import { + Component, + Directive as DirectiveSource, + Injectable, + NgModule, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { MockBuilder, MockRender } from 'ng-mocks'; @@ -54,12 +59,19 @@ describe('double-decorator:example-2', () => { name: 'mock', }); - beforeEach(() => MockBuilder(TargetComponent, TargetModule).mock(TargetProvider, myProviderMock())); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule).mock( + TargetProvider, + myProviderMock(), + ), + ); it('provides correct decoration of the directive', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toEqual('mock'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'mock', + ); }); }); }); diff --git a/tests/double-decorator/example-3.spec.ts b/tests/double-decorator/example-3.spec.ts index 6462652666..b93cab240f 100644 --- a/tests/double-decorator/example-3.spec.ts +++ b/tests/double-decorator/example-3.spec.ts @@ -1,6 +1,17 @@ -import { Component, Directive as DirectiveSource, Injectable, NgModule } from '@angular/core'; +import { + Component, + Directive as DirectiveSource, + Injectable, + NgModule, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; -import { MockBuilder, MockInstance, MockRender, MockReset, ngMocks } from 'ng-mocks'; +import { + MockBuilder, + MockInstance, + MockRender, + MockReset, + ngMocks, +} from 'ng-mocks'; // Because of A5 we need to cast Directive to any type // To let it accept 0 parameters. @@ -30,12 +41,16 @@ class ModuleWithComponent {} describe('double-decorator:example-3', () => { describe('default', () => { - beforeEach(() => TestBed.configureTestingModule({ declarations: [MyComponent] })); + beforeEach(() => + TestBed.configureTestingModule({ declarations: [MyComponent] }), + ); it('does not fail', () => { const fixture = MockRender(MyComponent); - expect(fixture.nativeElement.innerHTML).toEqual('directive'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'directive', + ); }); }); @@ -45,15 +60,23 @@ describe('double-decorator:example-3', () => { name: 'mock', }); - beforeAll(() => MockInstance(BaseClass, instance => ngMocks.stub(instance, myProviderMock()))); + beforeAll(() => + MockInstance(BaseClass, instance => + ngMocks.stub(instance, myProviderMock()), + ), + ); afterAll(MockReset); - beforeEach(() => MockBuilder(MyComponent, ModuleWithComponent).mock(BaseClass)); + beforeEach(() => + MockBuilder(MyComponent, ModuleWithComponent).mock(BaseClass), + ); it('does not fail', () => { const fixture = MockRender(MyComponent); - expect(fixture.nativeElement.innerHTML).toEqual('mock'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'mock', + ); }); }); @@ -63,12 +86,19 @@ describe('double-decorator:example-3', () => { name: 'mock', }); - beforeEach(() => MockBuilder(MyComponent, ModuleWithComponent).mock(BaseClass, myProviderMock())); + beforeEach(() => + MockBuilder(MyComponent, ModuleWithComponent).mock( + BaseClass, + myProviderMock(), + ), + ); it('does not fail', () => { const fixture = MockRender(MyComponent); - expect(fixture.nativeElement.innerHTML).toEqual('mock'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'mock', + ); }); }); }); diff --git a/tests/double-decorator/with-selector.spec.ts b/tests/double-decorator/with-selector.spec.ts index 7ba82e7019..35cf641c95 100644 --- a/tests/double-decorator/with-selector.spec.ts +++ b/tests/double-decorator/with-selector.spec.ts @@ -1,6 +1,17 @@ -import { Component, Directive as DirectiveSource, Injectable, NgModule } from '@angular/core'; +import { + Component, + Directive as DirectiveSource, + Injectable, + NgModule, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; -import { MockBuilder, MockInstance, MockRender, MockReset, ngMocks } from 'ng-mocks'; +import { + MockBuilder, + MockInstance, + MockRender, + MockReset, + ngMocks, +} from 'ng-mocks'; // Because of A5 we need to cast Directive to any type // To let it accept 0 parameters. @@ -35,12 +46,18 @@ class ModuleWithComponent {} describe('double-decorator:with-selector', () => { describe('default', () => { - beforeEach(() => TestBed.configureTestingModule({ imports: [ModuleWithComponent] }).compileComponents()); + beforeEach(() => + TestBed.configureTestingModule({ + imports: [ModuleWithComponent], + }).compileComponents(), + ); it('does not fail', () => { const fixture = MockRender(MyComponent); - expect(fixture.nativeElement.innerHTML).toContain('directive'); + expect(fixture.nativeElement.innerHTML).toContain( + 'directive', + ); }); }); @@ -49,16 +66,26 @@ describe('double-decorator:with-selector', () => { name: 'mock', }); - beforeEach(() => MockBuilder(MyComponent, ModuleWithComponent).exclude(BaseClass).mock(MyProvider)); + beforeEach(() => + MockBuilder(MyComponent, ModuleWithComponent) + .exclude(BaseClass) + .mock(MyProvider), + ); - beforeAll(() => MockInstance(MyProvider, instance => ngMocks.stub(instance, myProviderMock()))); + beforeAll(() => + MockInstance(MyProvider, instance => + ngMocks.stub(instance, myProviderMock()), + ), + ); afterAll(MockReset); it('provides correct decoration of the directive', () => { const fixture = MockRender(MyComponent); - expect(fixture.nativeElement.innerHTML).toContain('mock'); + expect(fixture.nativeElement.innerHTML).toContain( + 'mock', + ); }); }); @@ -67,22 +94,33 @@ describe('double-decorator:with-selector', () => { name: 'mock', }); - beforeEach(() => MockBuilder(MyComponent, ModuleWithComponent).mock(MyProvider, myProviderMock())); + beforeEach(() => + MockBuilder(MyComponent, ModuleWithComponent).mock( + MyProvider, + myProviderMock(), + ), + ); it('provides correct decoration of the directive', () => { const fixture = MockRender(MyComponent); - expect(fixture.nativeElement.innerHTML).toContain('mock'); + expect(fixture.nativeElement.innerHTML).toContain( + 'mock', + ); }); }); describe('keep', () => { - beforeEach(() => MockBuilder(MyComponent, ModuleWithComponent).keep(MyProvider)); + beforeEach(() => + MockBuilder(MyComponent, ModuleWithComponent).keep(MyProvider), + ); it('provides correct decoration of the directive', () => { const fixture = MockRender(MyComponent); - expect(fixture.nativeElement.innerHTML).toContain('directive'); + expect(fixture.nativeElement.innerHTML).toContain( + 'directive', + ); }); }); }); diff --git a/tests/double-decorator/without-selector-ivy.spec.ts b/tests/double-decorator/without-selector-ivy.spec.ts index 0ee5b00ba2..9e77554498 100644 --- a/tests/double-decorator/without-selector-ivy.spec.ts +++ b/tests/double-decorator/without-selector-ivy.spec.ts @@ -1,7 +1,12 @@ // tslint:disable no-duplicate-imports import * as core from '@angular/core'; -import { Component, Directive as DirectiveSource, Injectable, NgModule } from '@angular/core'; +import { + Component, + Directive as DirectiveSource, + Injectable, + NgModule, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { MockBuilder, MockRender } from 'ng-mocks'; @@ -42,35 +47,55 @@ describe('double-decorator-ivy:without-selector', () => { }); describe('default', () => { - beforeEach(() => TestBed.configureTestingModule({ imports: [ModuleWithComponent] }).compileComponents()); + beforeEach(() => + TestBed.configureTestingModule({ + imports: [ModuleWithComponent], + }).compileComponents(), + ); it('fails', () => { - expect(() => MockRender(MyComponent)).toThrowError(/Directive BaseClass has no selector/); + expect(() => MockRender(MyComponent)).toThrowError( + /Directive BaseClass has no selector/, + ); }); }); describe('hot-fix', () => { - beforeEach(() => MockBuilder(MyComponent, ModuleWithComponent).exclude(BaseClass).mock(MyProvider)); + beforeEach(() => + MockBuilder(MyComponent, ModuleWithComponent) + .exclude(BaseClass) + .mock(MyProvider), + ); it('fixes the issue via exclude', () => { const fixture = MockRender(MyComponent); - expect(fixture.nativeElement.innerHTML).toContain(''); + expect(fixture.nativeElement.innerHTML).toContain( + '', + ); }); }); describe('the-issue', () => { - beforeEach(() => MockBuilder(MyComponent, ModuleWithComponent).mock(MyProvider)); + beforeEach(() => + MockBuilder(MyComponent, ModuleWithComponent).mock(MyProvider), + ); it('fails', () => { - expect(() => MockRender(MyComponent)).toThrowError(/Directive MockOfBaseClass has no selector/); + expect(() => MockRender(MyComponent)).toThrowError( + /Directive MockOfBaseClass has no selector/, + ); }); }); describe('keep', () => { - beforeEach(() => MockBuilder(MyComponent, ModuleWithComponent).keep(MyProvider)); + beforeEach(() => + MockBuilder(MyComponent, ModuleWithComponent).keep(MyProvider), + ); it('fails', () => { - expect(() => MockRender(MyComponent)).toThrowError(/Directive MockOfBaseClass has no selector/); + expect(() => MockRender(MyComponent)).toThrowError( + /Directive MockOfBaseClass has no selector/, + ); }); }); }); diff --git a/tests/double-decorator/without-selector.spec.ts b/tests/double-decorator/without-selector.spec.ts index 51cea11a07..bb65be1429 100644 --- a/tests/double-decorator/without-selector.spec.ts +++ b/tests/double-decorator/without-selector.spec.ts @@ -1,6 +1,11 @@ // tslint:disable no-duplicate-imports -import { Component, Directive as DirectiveSource, Injectable, NgModule } from '@angular/core'; +import { + Component, + Directive as DirectiveSource, + Injectable, + NgModule, +} from '@angular/core'; import * as core from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { MockBuilder, MockRender } from 'ng-mocks'; @@ -44,31 +49,45 @@ describe('double-decorator:without-selector', () => { describe('default', () => { it('fails', async () => { try { - await TestBed.configureTestingModule({ imports: [ModuleWithComponent] }).compileComponents(); + await TestBed.configureTestingModule({ + imports: [ModuleWithComponent], + }).compileComponents(); fail('should fail'); } catch (error) { - expect(error.message).toMatch(/Directive BaseClass has no selector/); + expect(error.message).toMatch( + /Directive BaseClass has no selector/, + ); } }); }); // The only solution. describe('hot-fix', () => { - beforeEach(() => MockBuilder(MyComponent, ModuleWithComponent).exclude(BaseClass).mock(MyProvider)); + beforeEach(() => + MockBuilder(MyComponent, ModuleWithComponent) + .exclude(BaseClass) + .mock(MyProvider), + ); it('fixes the issue via exclude', () => { const fixture = MockRender(MyComponent); - expect(fixture.nativeElement.innerHTML).toContain(''); + expect(fixture.nativeElement.innerHTML).toContain( + '', + ); }); }); describe('the-issue', () => { it('fails', async () => { try { - await MockBuilder(MyComponent, ModuleWithComponent).mock(MyProvider); + await MockBuilder(MyComponent, ModuleWithComponent).mock( + MyProvider, + ); fail('should fail'); } catch (error) { - expect(error.message).toMatch(/Directive MockOfBaseClass has no selector/); + expect(error.message).toMatch( + /Directive MockOfBaseClass has no selector/, + ); } }); }); @@ -76,10 +95,14 @@ describe('double-decorator:without-selector', () => { describe('keep', () => { it('fails', async () => { try { - await MockBuilder(MyComponent, ModuleWithComponent).keep(MyProvider); + await MockBuilder(MyComponent, ModuleWithComponent).keep( + MyProvider, + ); fail('should fail'); } catch (error) { - expect(error.message).toMatch(/Directive MockOfBaseClass has no selector/); + expect(error.message).toMatch( + /Directive MockOfBaseClass has no selector/, + ); } }); }); diff --git a/tests/export-all/test.spec.ts b/tests/export-all/test.spec.ts index a4274cac87..ceca181c9d 100644 --- a/tests/export-all/test.spec.ts +++ b/tests/export-all/test.spec.ts @@ -1,7 +1,13 @@ // tslint:disable no-console import { CommonModule } from '@angular/common'; -import { Component, Input, NgModule, Pipe, PipeTransform } from '@angular/core'; +import { + Component, + Input, + NgModule, + Pipe, + PipeTransform, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { MockBuilder, MockRender } from 'ng-mocks'; @@ -17,7 +23,9 @@ class TargetPipe implements PipeTransform { @Component({ selector: 'target', - template: `{{ value | target }}`, + template: `{{ + value | target + }}`, }) class TargetComponent { @Input() public readonly value: string | null = null; @@ -73,7 +81,10 @@ describe('export-all', () => { describe('no-export', () => { it('fails on no exportAll due to lack of access to non-exported declarations', async () => { // Thanks A5 for any - const ngModule: any = MockBuilder().mock(TargetModule).exclude(TargetComponent).build(); + const ngModule: any = MockBuilder() + .mock(TargetModule) + .exclude(TargetComponent) + .build(); const testBed = TestBed.configureTestingModule({ ...ngModule, declarations: [...ngModule.declarations, TargetComponent], diff --git a/tests/exports-only/test.spec.ts b/tests/exports-only/test.spec.ts index 329da6ad1d..478e62fe3e 100644 --- a/tests/exports-only/test.spec.ts +++ b/tests/exports-only/test.spec.ts @@ -9,7 +9,9 @@ describe('ExportsOnly:real', () => { it('should render', () => { const fixture = MockRender(InternalComponent); expect(fixture).toBeDefined(); - expect(fixture.debugElement.nativeElement.innerHTML).toContain('internal'); + expect(fixture.nativeElement.innerHTML).toContain( + 'internal', + ); }); }); @@ -20,20 +22,26 @@ describe('ExportsOnly:mock1', () => { it('should render', () => { const fixture = MockRender(InternalComponent); expect(fixture).toBeDefined(); - const content = fixture.debugElement.nativeElement.innerHTML; - expect(content).toEqual(''); + const content = fixture.nativeElement.innerHTML; + expect(content).toEqual( + '', + ); }); }); describe('ExportsOnly:mock2', () => { - beforeEach(() => MockBuilder().mock(TargetModule).mock(InternalComponent)); + beforeEach(() => + MockBuilder().mock(TargetModule).mock(InternalComponent), + ); // The expectation is to see that InternalModule was exported and it can be accessed from the test. it('should render', () => { const fixture = MockRender(InternalComponent); expect(fixture).toBeDefined(); - const content = fixture.debugElement.nativeElement.innerHTML; - expect(content).toEqual(''); + const content = fixture.nativeElement.innerHTML; + expect(content).toEqual( + '', + ); }); }); @@ -44,6 +52,8 @@ describe('ExportsOnly:mock3', () => { it('should render', () => { const fixture = MockRender(InternalComponent); expect(fixture).toBeDefined(); - expect(fixture.debugElement.nativeElement.innerHTML).toContain('internal'); + expect(fixture.nativeElement.innerHTML).toContain( + 'internal', + ); }); }); diff --git a/tests/get-inputs-and-outputs/test.spec.ts b/tests/get-inputs-and-outputs/test.spec.ts index 990aa63a93..1bf6d78aae 100644 --- a/tests/get-inputs-and-outputs/test.spec.ts +++ b/tests/get-inputs-and-outputs/test.spec.ts @@ -2,7 +2,12 @@ import { MockBuilder, MockRender, ngMocks } from 'ng-mocks'; -import { Target2Directive, Target3Directive, TargetComponent, TargetModule } from './fixtures'; +import { + Target2Directive, + Target3Directive, + TargetComponent, + TargetModule, +} from './fixtures'; describe('get-inputs-and-outputs', () => { beforeEach(() => MockBuilder(TargetModule)); @@ -11,9 +16,18 @@ describe('get-inputs-and-outputs', () => { const params = { input1: '1', input2: '2', - output1: typeof jest !== 'undefined' ? jest.fn().mockName('output1') : jasmine.createSpy('output1'), - output2: typeof jest !== 'undefined' ? jest.fn().mockName('output2') : jasmine.createSpy('output2'), - output3: typeof jest !== 'undefined' ? jest.fn().mockName('output3') : jasmine.createSpy('output3'), + output1: + typeof jest !== 'undefined' + ? jest.fn().mockName('output1') + : jasmine.createSpy('output1'), + output2: + typeof jest !== 'undefined' + ? jest.fn().mockName('output2') + : jasmine.createSpy('output2'), + output3: + typeof jest !== 'undefined' + ? jest.fn().mockName('output3') + : jasmine.createSpy('output3'), }; const fixture = MockRender( ` { const componentElement = fixture.point; const component = fixture.point.componentInstance; - const directive2 = ngMocks.get(componentElement, Target2Directive); - const directive3 = ngMocks.get(componentElement, Target3Directive); + const directive2 = ngMocks.get( + componentElement, + Target2Directive, + ); + const directive3 = ngMocks.get( + componentElement, + Target3Directive, + ); expect(component.input).toEqual('1'); if ((params.output1 as any).mockReset) { @@ -63,8 +83,12 @@ describe('get-inputs-and-outputs', () => { // a really simple wait that allows us to skip pain of knowing directives. expect(ngMocks.input(componentElement, 'input1')).toEqual('1'); expect(ngMocks.input(componentElement, 'input2')).toEqual('2'); - expect(ngMocks.input(componentElement, 'inputUnused')).toEqual(undefined); - expect(() => ngMocks.input(componentElement, 'inputUndefined')).toThrowError( + expect(ngMocks.input(componentElement, 'inputUnused')).toEqual( + undefined, + ); + expect(() => + ngMocks.input(componentElement, 'inputUndefined'), + ).toThrowError( 'Cannot find inputUndefined input via ngMocks.input', ); expect(ngMocks.input(componentElement, 'input3')).toEqual('3'); @@ -90,7 +114,9 @@ describe('get-inputs-and-outputs', () => { } ngMocks.output(componentElement, 'output3').emit(); expect(params.output3).toHaveBeenCalled(); - expect(() => ngMocks.output(componentElement, 'outputUndefined')).toThrowError( + expect(() => + ngMocks.output(componentElement, 'outputUndefined'), + ).toThrowError( 'Cannot find outputUndefined output via ngMocks.output', ); }); diff --git a/tests/get-mocked-ng-def-of/test.spec.ts b/tests/get-mocked-ng-def-of/test.spec.ts index 9a11a35930..ef30100ece 100644 --- a/tests/get-mocked-ng-def-of/test.spec.ts +++ b/tests/get-mocked-ng-def-of/test.spec.ts @@ -1,5 +1,19 @@ -import { Component, Directive, NgModule, Pipe, PipeTransform } from '@angular/core'; -import { getMockedNgDefOf, MockBuilder, MockComponent, MockDirective, MockModule, MockPipe, ngMocks } from 'ng-mocks'; +import { + Component, + Directive, + NgModule, + Pipe, + PipeTransform, +} from '@angular/core'; +import { + getMockedNgDefOf, + MockBuilder, + MockComponent, + MockDirective, + MockModule, + MockPipe, + ngMocks, +} from 'ng-mocks'; @Pipe({ name: 'target', @@ -49,8 +63,12 @@ describe('getMockedNgDefOf:legacy', () => { it('throws an error outside of MockBuilder', () => { MockPipe(TargetPipe); - expect(() => getMockedNgDefOf(TargetPipe, 'p')).toThrowError(/There is no mock for TargetPipe/); - expect(() => getMockedNgDefOf(TargetPipe)).toThrowError(/There is no mock for TargetPipe/); + expect(() => getMockedNgDefOf(TargetPipe, 'p')).toThrowError( + /There is no mock for TargetPipe/, + ); + expect(() => getMockedNgDefOf(TargetPipe)).toThrowError( + /There is no mock for TargetPipe/, + ); }); }); diff --git a/tests/injected-ng-templates/injected-ng-templates.spec.ts b/tests/injected-ng-templates/injected-ng-templates.spec.ts index 2cb9ffb1ba..b04ee4abba 100644 --- a/tests/injected-ng-templates/injected-ng-templates.spec.ts +++ b/tests/injected-ng-templates/injected-ng-templates.spec.ts @@ -1,5 +1,10 @@ import { DebugElement } from '@angular/core'; -import { MockBuilder, MockComponent, MockRender, ngMocks } from 'ng-mocks'; +import { + MockBuilder, + MockComponent, + MockRender, + ngMocks, +} from 'ng-mocks'; import { CustomInjectionComponent } from './custom-injection.component'; @@ -20,9 +25,15 @@ describe('injected-ng-templates:real', () => { ); // every value should be rendered correctly. - expect(fixture.nativeElement.innerHTML).toContain('
    string1
    '); - expect(fixture.nativeElement.innerHTML).toContain('
    string2
    '); - expect(fixture.nativeElement.innerHTML).toContain('
    string3
    '); + expect(fixture.nativeElement.innerHTML).toContain( + '
    string1
    ', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '
    string2
    ', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '
    string3
    ', + ); }); }); @@ -48,10 +59,17 @@ describe('structural-directive-as-ng-for:mock', () => { ); // By default @ContentChild('block') shouldn't be rendered at all. - block = ngMocks.find(fixture.debugElement, '[data-key="block"]', undefined); + block = ngMocks.find( + fixture.debugElement, + '[data-key="block"]', + undefined, + ); expect(block).toBeUndefined(); - const mockComponent = ngMocks.find(fixture.debugElement, MockComponent(CustomInjectionComponent)).componentInstance; + const mockComponent = ngMocks.find( + fixture.debugElement, + MockComponent(CustomInjectionComponent), + ).componentInstance; // Now we want to render @ContentChild('block') with some context. mockComponent.__render('block', 'string1', { @@ -59,7 +77,9 @@ describe('structural-directive-as-ng-for:mock', () => { }); fixture.detectChanges(); block = ngMocks.find(fixture.debugElement, '[data-key="block"]'); - expect(block.nativeElement.innerHTML).toContain('
    string0 string1 test1
    '); + expect(block.nativeElement.innerHTML).toContain( + '
    string0 string1 test1
    ', + ); // Now we want to render @ContentChild('block') with another context. mockComponent.__render('block', 'string2', { @@ -67,6 +87,8 @@ describe('structural-directive-as-ng-for:mock', () => { }); fixture.detectChanges(); block = ngMocks.find(fixture.debugElement, '[data-key="block"]'); - expect(block.nativeElement.innerHTML).toContain('
    string0 string2 test2
    '); + expect(block.nativeElement.innerHTML).toContain( + '
    string0 string2 test2
    ', + ); }); }); diff --git a/tests/interceptor-kept-mocked/test.spec.ts b/tests/interceptor-kept-mocked/test.spec.ts index a6003f8d38..bc7ba850a0 100644 --- a/tests/interceptor-kept-mocked/test.spec.ts +++ b/tests/interceptor-kept-mocked/test.spec.ts @@ -7,7 +7,10 @@ import { HttpRequest, HTTP_INTERCEPTORS, } from '@angular/common/http'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { + HttpClientTestingModule, + HttpTestingController, +} from '@angular/common/http/testing'; import { Injectable, NgModule } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { MockBuilder, MockInstance, MockReset } from 'ng-mocks'; @@ -17,7 +20,10 @@ import { Observable } from 'rxjs'; class Target1Interceptor implements HttpInterceptor { protected value = '1'; - public intercept(request: HttpRequest, next: HttpHandler): Observable> { + public intercept( + request: HttpRequest, + next: HttpHandler, + ): Observable> { return next.handle( request.clone({ setHeaders: { @@ -32,7 +38,10 @@ class Target1Interceptor implements HttpInterceptor { class Target2Interceptor implements HttpInterceptor { protected value = '2'; - public intercept(request: HttpRequest, next: HttpHandler): Observable> { + public intercept( + request: HttpRequest, + next: HttpHandler, + ): Observable> { return next.handle( request.clone({ setHeaders: { @@ -73,7 +82,9 @@ describe('interceptor-kept-mock', () => { beforeAll(() => { MockInstance(Target2Interceptor, { - init: instance => (instance.intercept = (request, next) => next.handle(request)), + init: instance => + (instance.intercept = (request, next) => + next.handle(request)), }); }); @@ -81,7 +92,9 @@ describe('interceptor-kept-mock', () => { it('triggers interceptor', () => { const client: HttpClient = TestBed.get(HttpClient); - const httpMock: HttpTestingController = TestBed.get(HttpTestingController); + const httpMock: HttpTestingController = TestBed.get( + HttpTestingController, + ); // Let's do a simply request. client.get('/target').subscribe(); diff --git a/tests/internal-only-nested/test.spec.ts b/tests/internal-only-nested/test.spec.ts index f20c603bac..9f9a8682af 100644 --- a/tests/internal-only-nested/test.spec.ts +++ b/tests/internal-only-nested/test.spec.ts @@ -26,19 +26,27 @@ describe('InternalOnlyNested:real', () => { beforeEach(() => MockBuilder(TargetModule)); it('should render', () => { - expect(() => MockRender(InternalComponent)).toThrowError(/'internal-component' is not a known element/); + expect(() => MockRender(InternalComponent)).toThrowError( + /'internal-component' is not a known element/, + ); }); }); describe('InternalOnlyNested:mock', () => { - beforeEach(() => MockBuilder().mock(TargetModule).mock(InternalComponent, { export: true })); + beforeEach(() => + MockBuilder() + .mock(TargetModule) + .mock(InternalComponent, { export: true }), + ); // The expectation is to see that InternalComponent was exported to the level of the TestingModule // and can be accessed in the test even it was deeply nested. it('should render', () => { const fixture = MockRender(InternalComponent); expect(fixture).toBeDefined(); - const content = fixture.debugElement.nativeElement.innerHTML; - expect(content).toEqual(''); + const content = fixture.nativeElement.innerHTML; + expect(content).toEqual( + '', + ); }); }); diff --git a/tests/internal-only/test.spec.ts b/tests/internal-only/test.spec.ts index 09984ebc3f..c5fd568314 100644 --- a/tests/internal-only/test.spec.ts +++ b/tests/internal-only/test.spec.ts @@ -26,18 +26,26 @@ describe('InternalOnly:real', () => { beforeEach(() => MockBuilder(TargetModule)); it('should render', () => { - expect(() => MockRender(InternalComponent)).toThrowError(/'internal-component' is not a known element/); + expect(() => MockRender(InternalComponent)).toThrowError( + /'internal-component' is not a known element/, + ); }); }); describe('InternalOnly:mock', () => { - beforeEach(() => MockBuilder().mock(TargetModule).mock(InternalComponent, { export: true })); + beforeEach(() => + MockBuilder() + .mock(TargetModule) + .mock(InternalComponent, { export: true }), + ); // The expectation is to see that InternalComponent was exported and can be accessed from the test. it('should render', () => { const fixture = MockRender(InternalComponent); expect(fixture).toBeDefined(); - const content = fixture.debugElement.nativeElement.innerHTML; - expect(content).toEqual(''); + const content = fixture.nativeElement.innerHTML; + expect(content).toEqual( + '', + ); }); }); diff --git a/tests/internal-vs-external/test.spec.ts b/tests/internal-vs-external/test.spec.ts index 9282db027a..2d66cc3cc9 100644 --- a/tests/internal-vs-external/test.spec.ts +++ b/tests/internal-vs-external/test.spec.ts @@ -2,7 +2,10 @@ import { MockBuilder, MockRender } from 'ng-mocks'; -import { ExternalComponent, InternalComponent } from './fixtures.components'; +import { + ExternalComponent, + InternalComponent, +} from './fixtures.components'; import { TargetModule } from './fixtures.modules'; describe('InternalVsExternal:real', () => { @@ -28,10 +31,14 @@ describe('InternalVsExternal:real', () => { it('should render', () => { const fixture = MockRender(ExternalComponent); expect(fixture).toBeDefined(); - const content = fixture.debugElement.nativeElement.innerHTML; - expect(content).toContain('external internal'); - - expect(() => MockRender(InternalComponent)).toThrowError(/'internal-component' is not a known element/); + const content = fixture.nativeElement.innerHTML; + expect(content).toContain( + 'external internal', + ); + + expect(() => MockRender(InternalComponent)).toThrowError( + /'internal-component' is not a known element/, + ); }); }); @@ -59,10 +66,14 @@ describe('InternalVsExternal:mock', () => { it('should render', () => { const fixture = MockRender(ExternalComponent); expect(fixture).toBeDefined(); - const content = fixture.debugElement.nativeElement.innerHTML; - expect(content).toEqual(''); - - expect(() => MockRender(InternalComponent)).toThrowError(/'internal-component' is not a known element/); + const content = fixture.nativeElement.innerHTML; + expect(content).toEqual( + '', + ); + + expect(() => MockRender(InternalComponent)).toThrowError( + /'internal-component' is not a known element/, + ); }); }); @@ -72,8 +83,10 @@ describe('InternalVsExternal:legacy', () => { it('should render', () => { const fixture = MockRender(ExternalComponent); expect(fixture).toBeDefined(); - const content = fixture.debugElement.nativeElement.innerHTML; - expect(content).toEqual(''); + const content = fixture.nativeElement.innerHTML; + expect(content).toEqual( + '', + ); // the code below will fail because the MockModule outside of the MockBuilder exports everything. // try { diff --git a/tests/is-mock-of/test.spec.ts b/tests/is-mock-of/test.spec.ts index b4424cf1af..a0ad436716 100644 --- a/tests/is-mock-of/test.spec.ts +++ b/tests/is-mock-of/test.spec.ts @@ -1,5 +1,17 @@ -import { Component, Directive, NgModule, Pipe, PipeTransform } from '@angular/core'; -import { isMockOf, MockComponent, MockDirective, MockModule, MockPipe } from 'ng-mocks'; +import { + Component, + Directive, + NgModule, + Pipe, + PipeTransform, +} from '@angular/core'; +import { + isMockOf, + MockComponent, + MockDirective, + MockModule, + MockPipe, +} from 'ng-mocks'; @Pipe({ name: 'target', @@ -32,7 +44,9 @@ describe('isMockOf', () => { it('detects module', () => { const mock = MockModule(TargetModule); expect(isMockOf(new mock(), TargetModule, 'm')).toBeTruthy(); - expect(isMockOf(new TargetModule(), TargetModule, 'm')).toBeFalsy(); + expect( + isMockOf(new TargetModule(), TargetModule, 'm'), + ).toBeFalsy(); }); it('detects pipe', () => { @@ -44,18 +58,24 @@ describe('isMockOf', () => { it('detects directive', () => { const mock = MockDirective(TargetDirective); expect(isMockOf(new mock(), TargetDirective, 'd')).toBeTruthy(); - expect(isMockOf(new TargetDirective(), TargetDirective, 'd')).toBeFalsy(); + expect( + isMockOf(new TargetDirective(), TargetDirective, 'd'), + ).toBeFalsy(); }); it('detects components', () => { const mock = MockComponent(TargetComponent); expect(isMockOf(new mock(), TargetComponent, 'c')).toBeTruthy(); - expect(isMockOf(new TargetComponent(), TargetComponent, 'c')).toBeFalsy(); + expect( + isMockOf(new TargetComponent(), TargetComponent, 'c'), + ).toBeFalsy(); }); it('detects mocks', () => { const mock = MockComponent(TargetComponent); expect(isMockOf(new mock(), TargetComponent)).toBeTruthy(); - expect(isMockOf(new TargetComponent(), TargetComponent)).toBeFalsy(); + expect( + isMockOf(new TargetComponent(), TargetComponent), + ).toBeFalsy(); }); }); diff --git a/tests/is-mocked-ng-def-of/test.spec.ts b/tests/is-mocked-ng-def-of/test.spec.ts index ac99ba4323..ee109434de 100644 --- a/tests/is-mocked-ng-def-of/test.spec.ts +++ b/tests/is-mocked-ng-def-of/test.spec.ts @@ -1,5 +1,17 @@ -import { Component, Directive, NgModule, Pipe, PipeTransform } from '@angular/core'; -import { isMockedNgDefOf, MockComponent, MockDirective, MockModule, MockPipe } from 'ng-mocks'; +import { + Component, + Directive, + NgModule, + Pipe, + PipeTransform, +} from '@angular/core'; +import { + isMockedNgDefOf, + MockComponent, + MockDirective, + MockModule, + MockPipe, +} from 'ng-mocks'; @Pipe({ name: 'target', diff --git a/tests/issue-142/test.spec.ts b/tests/issue-142/test.spec.ts index 6b7aeffe09..fe3ed16169 100644 --- a/tests/issue-142/test.spec.ts +++ b/tests/issue-142/test.spec.ts @@ -1,4 +1,9 @@ -import { Component, Inject, InjectionToken, NgModule } from '@angular/core'; +import { + Component, + Inject, + InjectionToken, + NgModule, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { MockModule } from 'ng-mocks'; @@ -19,7 +24,9 @@ export class TargetModule { }; } - public constructor(@Inject(TARGET_TOKEN) public readonly targetToken: boolean) {} + public constructor( + @Inject(TARGET_TOKEN) public readonly targetToken: boolean, + ) {} } @Component({ diff --git a/tests/issue-151/test.spec.ts b/tests/issue-151/test.spec.ts index 3ab0013df9..c0194c6a95 100644 --- a/tests/issue-151/test.spec.ts +++ b/tests/issue-151/test.spec.ts @@ -12,7 +12,10 @@ describe('issue-151', () => { describe('mock AppRoutingModule', () => { beforeEach(() => TestBed.configureTestingModule( - MockBuilder(AppComponent, AppModule).keep(RouterModule).keep(RouterTestingModule).build(), + MockBuilder(AppComponent, AppModule) + .keep(RouterModule) + .keep(RouterTestingModule) + .build(), ), ); @@ -27,7 +30,9 @@ describe('issue-151', () => { it('should create the app', () => { // asserting that app-hello is replaced with a mock copy (no content) and detected by router. - expect(fixture.nativeElement.innerHTML).toContain(''); + expect(fixture.nativeElement.innerHTML).toContain( + '', + ); }); }); }); diff --git a/tests/issue-157/test.spec.ts b/tests/issue-157/test.spec.ts index 9417d07cef..73fc499160 100644 --- a/tests/issue-157/test.spec.ts +++ b/tests/issue-157/test.spec.ts @@ -1,6 +1,12 @@ // tslint:disable max-file-line-count -import { Component, Directive, forwardRef, Optional, Self } from '@angular/core'; +import { + Component, + Directive, + forwardRef, + Optional, + Self, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { ControlValueAccessor, @@ -22,7 +28,8 @@ export class ActualEmptyComponent {} selector: 'actual-injection', template: '', }) -export class ActualInjectionComponent implements ControlValueAccessor { +export class ActualInjectionComponent + implements ControlValueAccessor { protected value: any; public constructor(@Self() @Optional() ngControl: NgControl) { @@ -109,7 +116,12 @@ export class ActualTokenDirective implements ControlValueAccessor { describe('issue-157:real', () => { beforeEach(() => TestBed.configureTestingModule({ - declarations: [ActualEmptyComponent, ActualInjectionComponent, ActualTokenComponent, ActualTokenDirective], + declarations: [ + ActualEmptyComponent, + ActualInjectionComponent, + ActualTokenComponent, + ActualTokenDirective, + ], imports: [ReactiveFormsModule], }).compileComponents(), ); diff --git a/tests/issue-162/test.spec.ts b/tests/issue-162/test.spec.ts index 1a2bffc90e..e23ec79d35 100644 --- a/tests/issue-162/test.spec.ts +++ b/tests/issue-162/test.spec.ts @@ -2,7 +2,10 @@ import { Component, NgModule, RendererFactory2 } from '@angular/core'; import { TestBed } from '@angular/core/testing'; -import { BrowserModule, EventManager } from '@angular/platform-browser'; +import { + BrowserModule, + EventManager, +} from '@angular/platform-browser'; import { MockBuilder, MockRender, ngMocks } from 'ng-mocks'; @Component({ @@ -37,7 +40,9 @@ describe('issue-162', () => { TestBed.resetTestingModule(); const target: EventManager = TestBed.get(EventManager); expect(target.addEventListener).toEqual(jasmine.any(Function)); - expect((target.addEventListener as any).__ngMocks).toBeUndefined(); + expect( + (target.addEventListener as any).__ngMocks, + ).toBeUndefined(); TestBed.resetTestingModule(); }); @@ -60,12 +65,28 @@ describe('issue-162', () => { // creating spies if (typeof jest !== 'undefined') { - getSpy = jest.spyOn(fixture.point.componentInstance, 'title', 'get'); - setSpy = jest.spyOn(fixture.point.componentInstance, 'title', 'set'); + getSpy = jest.spyOn( + fixture.point.componentInstance, + 'title', + 'get', + ); + setSpy = jest.spyOn( + fixture.point.componentInstance, + 'title', + 'set', + ); getSpy.mockReturnValue('spy'); } else if (typeof jasmine !== 'undefined') { - getSpy = spyOnProperty(fixture.point.componentInstance, 'title', 'get'); - setSpy = spyOnProperty(fixture.point.componentInstance, 'title', 'set'); + getSpy = spyOnProperty( + fixture.point.componentInstance, + 'title', + 'get', + ); + setSpy = spyOnProperty( + fixture.point.componentInstance, + 'title', + 'set', + ); getSpy.and.returnValue('spy'); } diff --git a/tests/issue-166/test.spec.ts b/tests/issue-166/test.spec.ts index f92c008ec8..ccd86ad1d9 100644 --- a/tests/issue-166/test.spec.ts +++ b/tests/issue-166/test.spec.ts @@ -21,7 +21,8 @@ class MyService { describe('issue-166', () => { it('accepts spies', () => { - const spy = typeof jest !== 'undefined' ? jest.fn() : jasmine.createSpy(); + const spy = + typeof jest !== 'undefined' ? jest.fn() : jasmine.createSpy(); const stub = ngMocks.stub(MockService(MyService), { onErrorSet$: new Subject(), onWarningSet$: new Subject(), diff --git a/tests/issue-167/NG_VALIDATORS.spec.ts b/tests/issue-167/NG_VALIDATORS.spec.ts index dbb7cb5ef2..4b7f42699c 100644 --- a/tests/issue-167/NG_VALIDATORS.spec.ts +++ b/tests/issue-167/NG_VALIDATORS.spec.ts @@ -1,6 +1,17 @@ -import { Component, Directive, forwardRef, NgModule } from '@angular/core'; +import { + Component, + Directive, + forwardRef, + NgModule, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; -import { FormControl, NG_VALIDATORS, ReactiveFormsModule, ValidationErrors, Validator } from '@angular/forms'; +import { + FormControl, + NG_VALIDATORS, + ReactiveFormsModule, + ValidationErrors, + Validator, +} from '@angular/forms'; import { MockBuilder, MockRender, ngMocks } from 'ng-mocks'; @Directive({ @@ -63,12 +74,19 @@ describe('issue-167:NG_VALIDATORS:real', () => { }); describe('issue-167:NG_VALIDATORS:mock', () => { - beforeEach(() => MockBuilder(RealComponent, TargetModule).keep(ReactiveFormsModule)); + beforeEach(() => + MockBuilder(RealComponent, TargetModule).keep( + ReactiveFormsModule, + ), + ); it('should trigger validation w/o an error', () => { const fixture = MockRender(RealComponent); - const mock = ngMocks.findInstance(fixture.debugElement, TargetDirective); + const mock = ngMocks.findInstance( + fixture.debugElement, + TargetDirective, + ); spyOn(mock, 'validate').and.returnValue({ mock: true, }); diff --git a/tests/issue-167/component.spec.ts b/tests/issue-167/component.spec.ts index 8926329aec..2ed8418429 100644 --- a/tests/issue-167/component.spec.ts +++ b/tests/issue-167/component.spec.ts @@ -27,7 +27,8 @@ import { MockBuilder, MockRender, ngMocks } from 'ng-mocks'; selector: 'target', template: 'target', }) -export class TargetComponent implements ControlValueAccessor, Validator { +export class TargetComponent + implements ControlValueAccessor, Validator { public valRegisterOnChange: any; public valRegisterOnTouched: any; public valRegisterOnValidatorChange: any; @@ -92,7 +93,8 @@ describe('issue-167:component:real', () => { it('should create an instance', () => { const fixture = MockRender(RealComponent); - const mock = ngMocks.find(fixture.debugElement, TargetComponent).componentInstance; + const mock = ngMocks.find(fixture.debugElement, TargetComponent) + .componentInstance; spyOn(mock, 'validate').and.returnValue({ updated: true, }); @@ -108,12 +110,17 @@ describe('issue-167:component:real', () => { }); describe('issue-167:component:mock', () => { - beforeEach(() => MockBuilder(RealComponent, TargetModule).keep(ReactiveFormsModule)); + beforeEach(() => + MockBuilder(RealComponent, TargetModule).keep( + ReactiveFormsModule, + ), + ); it('should create an instance', () => { const fixture = MockRender(RealComponent); - const mock = ngMocks.find(fixture.debugElement, TargetComponent).componentInstance; + const mock = ngMocks.find(fixture.debugElement, TargetComponent) + .componentInstance; spyOn(mock, 'validate').and.returnValue({ updated: true, }); diff --git a/tests/issue-167/directive.spec.ts b/tests/issue-167/directive.spec.ts index b45fa299b6..0ae15b9f8d 100644 --- a/tests/issue-167/directive.spec.ts +++ b/tests/issue-167/directive.spec.ts @@ -1,4 +1,9 @@ -import { Component, Directive, forwardRef, NgModule } from '@angular/core'; +import { + Component, + Directive, + forwardRef, + NgModule, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { ControlValueAccessor, @@ -26,7 +31,8 @@ import { MockBuilder, MockRender, ngMocks } from 'ng-mocks'; ], selector: '[target]', }) -export class TargetDirective implements ControlValueAccessor, Validator { +export class TargetDirective + implements ControlValueAccessor, Validator { public valRegisterOnChange: any; public valRegisterOnTouched: any; public valRegisterOnValidatorChange: any; @@ -91,7 +97,9 @@ describe('issue-167:directive:real', () => { it('should create an instance', () => { const fixture = MockRender(RealComponent); - const mock = ngMocks.find(fixture.debugElement, TargetDirective).injector.get(TargetDirective); + const mock = ngMocks + .find(fixture.debugElement, TargetDirective) + .injector.get(TargetDirective); spyOn(mock, 'validate').and.returnValue({ updated: true, }); @@ -107,12 +115,18 @@ describe('issue-167:directive:real', () => { }); describe('issue-167:directive:mock', () => { - beforeEach(() => MockBuilder(RealComponent, TargetModule).keep(ReactiveFormsModule)); + beforeEach(() => + MockBuilder(RealComponent, TargetModule).keep( + ReactiveFormsModule, + ), + ); it('should create an instance', () => { const fixture = MockRender(RealComponent); - const mock = ngMocks.find(fixture.debugElement, TargetDirective).injector.get(TargetDirective); + const mock = ngMocks + .find(fixture.debugElement, TargetDirective) + .injector.get(TargetDirective); spyOn(mock, 'validate').and.returnValue({ updated: true, }); diff --git a/tests/issue-170/test.spec.ts b/tests/issue-170/test.spec.ts index 8f42472bb3..3411f281ba 100644 --- a/tests/issue-170/test.spec.ts +++ b/tests/issue-170/test.spec.ts @@ -1,5 +1,15 @@ -import { AfterViewInit, Component, Injectable, ViewChild } from '@angular/core'; -import { MockBuilder, MockInstance, MockRender, MockReset } from 'ng-mocks'; +import { + AfterViewInit, + Component, + Injectable, + ViewChild, +} from '@angular/core'; +import { + MockBuilder, + MockInstance, + MockRender, + MockReset, +} from 'ng-mocks'; import { staticFalse } from '..'; @@ -37,7 +47,8 @@ export class TargetComponent { template: '', }) export class RealComponent implements AfterViewInit { - @ViewChild(TargetComponent, staticFalse) protected child?: TargetComponent; + @ViewChild(TargetComponent, staticFalse) + protected child?: TargetComponent; public ngAfterViewInit() { if (this.child) { diff --git a/tests/issue-172/test.spec.ts b/tests/issue-172/test.spec.ts index c629d07208..7a4a3efd0a 100644 --- a/tests/issue-172/test.spec.ts +++ b/tests/issue-172/test.spec.ts @@ -1,4 +1,9 @@ -import { Component, Injectable, NgModule, OnInit } from '@angular/core'; +import { + Component, + Injectable, + NgModule, + OnInit, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { MockBuilder, MockRender } from 'ng-mocks'; @@ -53,7 +58,9 @@ describe('issue-172:real', () => { it('renders echo', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain('Target1ServiceTarget2Service'); + expect(fixture.nativeElement.innerHTML).toContain( + 'Target1ServiceTarget2Service', + ); }); }); @@ -81,7 +88,9 @@ describe('issue-172:test', () => { }, }); const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain('MockServiceTarget2Service'); + expect(fixture.nativeElement.innerHTML).toContain( + 'MockServiceTarget2Service', + ); }); }); @@ -94,7 +103,9 @@ describe('issue-172:mock', () => { it('renders the mock echo', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain('MockServiceTarget2Service'); + expect(fixture.nativeElement.innerHTML).toContain( + 'MockServiceTarget2Service', + ); }); }); @@ -107,6 +118,8 @@ describe('issue-172:restore', () => { it('renders echo', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain('Target1ServiceTarget2Service'); + expect(fixture.nativeElement.innerHTML).toContain( + 'Target1ServiceTarget2Service', + ); }); }); diff --git a/tests/issue-175/fixtures.ts b/tests/issue-175/fixtures.ts new file mode 100644 index 0000000000..5512930f3a --- /dev/null +++ b/tests/issue-175/fixtures.ts @@ -0,0 +1,80 @@ +import { Component, Directive, Injectable, NgModule, Pipe, PipeTransform } from '@angular/core'; + +@Injectable() +export class Target1Service {} + +@Injectable() +export class Target2Service {} + +@Component({ + providers: [Target1Service], + selector: 'com-1', + template: 'com-1', +}) +export class Target1Component { + public constructor(public service: Target1Service) {} +} + +@Component({ + selector: 'com-2', + template: 'com-2', +}) +export class Target2Component { + public constructor(public service: Target2Service) {} +} + +@Directive({ + providers: [Target1Service], + selector: 'dir-1', +}) +export class Target1Directive { + public constructor(public service: Target1Service) {} +} + +@Directive({ + selector: 'dir-2', +}) +export class Target2Directive { + public constructor(public service: Target2Service) {} +} + +@Pipe({ + name: 'pip1', +}) +export class Target1Pipe implements PipeTransform { + protected name = 'pip1'; + + public transform(): string { + return this.name; + } +} + +@Pipe({ + name: 'pip2', +}) +export class Target2Pipe implements PipeTransform { + protected name = 'pip2'; + + public transform(): string { + return this.name; + } +} + +@NgModule({ + declarations: [Target1Component, Target1Directive, Target1Pipe], + exports: [Target1Component, Target1Directive, Target1Pipe], +}) +export class Target1Module {} + +@NgModule({ + declarations: [Target2Component, Target2Directive, Target2Pipe], + exports: [Target2Component, Target2Directive, Target2Pipe], + providers: [Target2Service], +}) +export class Target2Module {} + +@NgModule({ + exports: [Target1Module, Target2Module], + imports: [Target1Module, Target2Module], +}) +export class TargetModule {} diff --git a/tests/issue-175/test.spec.ts b/tests/issue-175/test.spec.ts index cd38c34cfc..b8370c9176 100644 --- a/tests/issue-175/test.spec.ts +++ b/tests/issue-175/test.spec.ts @@ -1,87 +1,20 @@ // tslint:disable no-console -import { Component, Directive, Injectable, NgModule, Pipe, PipeTransform } from '@angular/core'; +import { NgModule } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { MockBuilder, MockRender } from 'ng-mocks'; -@Injectable() -class Target1Service {} - -@Injectable() -class Target2Service {} - -@Component({ - providers: [Target1Service], - selector: 'com-1', - template: 'com-1', -}) -class Target1Component { - public constructor(public service: Target1Service) {} -} - -@Component({ - selector: 'com-2', - template: 'com-2', -}) -class Target2Component { - public constructor(public service: Target2Service) {} -} - -@Directive({ - providers: [Target1Service], - selector: 'dir-1', -}) -class Target1Directive { - public constructor(public service: Target1Service) {} -} - -@Directive({ - selector: 'dir-2', -}) -class Target2Directive { - public constructor(public service: Target2Service) {} -} - -@Pipe({ - name: 'pip1', -}) -class Target1Pipe implements PipeTransform { - protected name = 'pip1'; - - public transform(): string { - return this.name; - } -} - -@Pipe({ - name: 'pip2', -}) -class Target2Pipe implements PipeTransform { - protected name = 'pip2'; - - public transform(): string { - return this.name; - } -} - -@NgModule({ - declarations: [Target1Component, Target1Directive, Target1Pipe], - exports: [Target1Component, Target1Directive, Target1Pipe], -}) -class Target1Module {} - -@NgModule({ - declarations: [Target2Component, Target2Directive, Target2Pipe], - exports: [Target2Component, Target2Directive, Target2Pipe], - providers: [Target2Service], -}) -class Target2Module {} - -@NgModule({ - exports: [Target1Module, Target2Module], - imports: [Target1Module, Target2Module], -}) -class TargetModule {} +import { + Target1Component, + Target1Directive, + Target1Pipe, + Target1Service, + Target2Component, + Target2Directive, + Target2Module, + Target2Service, + TargetModule, +} from './fixtures'; describe('issue-175', () => { // Thanks Ivy, it doesn't throw an error and we have to use injector. @@ -102,42 +35,62 @@ describe('issue-175', () => { }); describe('module', () => { - beforeEach(() => MockBuilder(TargetModule).exclude(Target2Module)); + beforeEach(() => + MockBuilder(TargetModule).exclude(Target2Module), + ); it('fails', () => { - expect(() => MockRender(Target2Component)).toThrowError(/'com-2' is not a known element/); + expect(() => MockRender(Target2Component)).toThrowError( + /'com-2' is not a known element/, + ); }); }); describe('module:component', () => { - beforeEach(() => MockBuilder(TargetModule).exclude(Target1Component)); + beforeEach(() => + MockBuilder(TargetModule).exclude(Target1Component), + ); it('fails', () => { - expect(() => MockRender(Target1Component)).toThrowError(/'com-1' is not a known element/); + expect(() => MockRender(Target1Component)).toThrowError( + /'com-1' is not a known element/, + ); }); }); describe('module:component:service', () => { - beforeEach(() => MockBuilder(TargetModule).exclude(Target1Service)); + beforeEach(() => + MockBuilder(TargetModule).exclude(Target1Service), + ); it('fails', () => { - expect(() => MockRender(Target1Component)).toThrowError(/No provider for Target1Service/); + expect(() => MockRender(Target1Component)).toThrowError( + /No provider for Target1Service/, + ); }); }); describe('module:directive', () => { - beforeEach(() => MockBuilder(TargetModule).exclude(Target2Directive)); + beforeEach(() => + MockBuilder(TargetModule).exclude(Target2Directive), + ); it('fails', () => { - expect(() => MockRender(``)).toThrowError(/'dir-2' is not a known element/); + expect(() => MockRender(``)).toThrowError( + /'dir-2' is not a known element/, + ); }); }); describe('module:directive:service', () => { - beforeEach(() => MockBuilder(TargetModule).exclude(Target1Service)); + beforeEach(() => + MockBuilder(TargetModule).exclude(Target1Service), + ); it('fails', () => { - expect(() => MockRender(``)).toThrowError(/No provider for Target1Service/); + expect(() => MockRender(``)).toThrowError( + /No provider for Target1Service/, + ); }); }); @@ -145,47 +98,70 @@ describe('issue-175', () => { beforeEach(() => MockBuilder(TargetModule).exclude(Target1Pipe)); it('fails', () => { - expect(() => MockRender(`{{ 'test' | pip1 }}`)).toThrowError(/The pipe 'pip1' could not be found/); + expect(() => MockRender(`{{ 'test' | pip1 }}`)).toThrowError( + /The pipe 'pip1' could not be found/, + ); }); }); describe('module:service', () => { - beforeEach(() => MockBuilder(TargetModule).exclude(Target2Service)); + beforeEach(() => + MockBuilder(TargetModule).exclude(Target2Service), + ); it('fails', () => { - expect(() => MockRender(Target2Component)).toThrowError(/No provider for Target2Service/); + expect(() => MockRender(Target2Component)).toThrowError( + /No provider for Target2Service/, + ); }); }); describe('component:service', () => { - beforeEach(() => MockBuilder(Target1Component).exclude(Target1Service)); + beforeEach(() => + MockBuilder(Target1Component).exclude(Target1Service), + ); it('fails', () => { - expect(() => MockRender(Target1Component)).toThrowError(/No provider for Target1Service/); + expect(() => MockRender(Target1Component)).toThrowError( + /No provider for Target1Service/, + ); }); }); describe('directive:service', () => { - beforeEach(() => MockBuilder(Target1Directive).exclude(Target1Service)); + beforeEach(() => + MockBuilder(Target1Directive).exclude(Target1Service), + ); it('fails', () => { - expect(() => MockRender(``)).toThrowError(/No provider for Target1Service/); + expect(() => MockRender(``)).toThrowError( + /No provider for Target1Service/, + ); }); }); describe('beforeAll:component via createComponent', () => { let ngModule: NgModule; - beforeAll(() => (ngModule = MockBuilder(Target1Component).exclude(Target1Service).build())); + beforeAll( + () => + (ngModule = MockBuilder(Target1Component) + .exclude(Target1Service) + .build()), + ); beforeEach(() => { TestBed.configureTestingModule(ngModule); }); it('fails first time via TestBed.createComponent', () => { - expect(() => TestBed.createComponent(Target1Component)).toThrowError(/No provider for Target1Service/); + expect(() => + TestBed.createComponent(Target1Component), + ).toThrowError(/No provider for Target1Service/); }); it('fails second time via TestBed.createComponent', () => { - expect(() => TestBed.createComponent(Target1Component)).toThrowError(/No provider for Target1Service/); + expect(() => + TestBed.createComponent(Target1Component), + ).toThrowError(/No provider for Target1Service/); }); }); @@ -193,39 +169,66 @@ describe('issue-175', () => { let ngModule: NgModule; describe('exclude', () => { - beforeAll(() => (ngModule = MockBuilder(Target1Component).exclude(Target1Service).build())); - beforeEach(() => TestBed.configureTestingModule(ngModule).compileComponents()); + beforeAll( + () => + (ngModule = MockBuilder(Target1Component) + .exclude(Target1Service) + .build()), + ); + beforeEach(() => + TestBed.configureTestingModule(ngModule).compileComponents(), + ); it('fails first time via TestBed.createComponent', () => { - expect(() => TestBed.createComponent(Target1Component)).toThrowError(/No provider for Target1Service/); + expect(() => + TestBed.createComponent(Target1Component), + ).toThrowError(/No provider for Target1Service/); }); it('fails second time via TestBed.createComponent', () => { - expect(() => TestBed.createComponent(Target1Component)).toThrowError(/No provider for Target1Service/); + expect(() => + TestBed.createComponent(Target1Component), + ).toThrowError(/No provider for Target1Service/); }); }); describe('normal', () => { beforeAll(() => (ngModule = MockBuilder(TargetModule).build())); - beforeEach(() => TestBed.configureTestingModule(ngModule).compileComponents()); + beforeEach(() => + TestBed.configureTestingModule(ngModule).compileComponents(), + ); it('should not fail anymore via TestBed.createComponent', () => { - expect(() => TestBed.createComponent(Target1Component)).not.toThrowError(/No provider for Target1Service/); + // No provider for Target1Service + expect(() => + TestBed.createComponent(Target1Component), + ).not.toThrow(); }); }); }); describe('beforeAll:directive', () => { let ngModule: NgModule; - beforeAll(() => (ngModule = MockBuilder(Target1Directive).exclude(Target1Service).build())); - beforeEach(() => TestBed.configureTestingModule(ngModule).compileComponents()); + beforeAll( + () => + (ngModule = MockBuilder(Target1Directive) + .exclude(Target1Service) + .build()), + ); + beforeEach(() => + TestBed.configureTestingModule(ngModule).compileComponents(), + ); it('fails first time via MockRender', () => { - expect(() => MockRender(``)).toThrowError(/No provider for Target1Service/); + expect(() => MockRender(``)).toThrowError( + /No provider for Target1Service/, + ); }); it('fails second time via MockRender', () => { - expect(() => MockRender(``)).toThrowError(/No provider for Target1Service/); + expect(() => MockRender(``)).toThrowError( + /No provider for Target1Service/, + ); }); }); }); diff --git a/tests/issue-177/test.spec.ts b/tests/issue-177/test.spec.ts index ba1487a9ff..ca838e50d0 100644 --- a/tests/issue-177/test.spec.ts +++ b/tests/issue-177/test.spec.ts @@ -3,7 +3,8 @@ import { MockService, ngMocks } from 'ng-mocks'; class Example { private readonly privateDynamicGet = 'return value from dynamicGet'; - private readonly privateDynamicMethod = 'return value from dynamicMethod'; + private readonly privateDynamicMethod = + 'return value from dynamicMethod'; public get dynamicGet() { return this.privateDynamicGet; diff --git a/tests/issue-178/test.spec.ts b/tests/issue-178/test.spec.ts index 3e3cd44e42..6ca422679e 100644 --- a/tests/issue-178/test.spec.ts +++ b/tests/issue-178/test.spec.ts @@ -41,7 +41,11 @@ class HelloModule {} describe('issue-178', () => { beforeEach( - () => MockBuilder(HelloComponent, HelloModule).replace(RouterModule, RouterTestingModule), // <- causes the issue + () => + MockBuilder(HelloComponent, HelloModule).replace( + RouterModule, + RouterTestingModule, + ), // <- causes the issue ); it('should create the component', () => { diff --git a/tests/issue-181/test.spec.ts b/tests/issue-181/test.spec.ts index f051dc7d24..059fc36fae 100644 --- a/tests/issue-181/test.spec.ts +++ b/tests/issue-181/test.spec.ts @@ -38,8 +38,14 @@ describe('issue-181:real', () => { `); - expect(ngMocks.findInstance(fixture.debugElement, TargetComponent).header).toBeTruthy(); - expect(ngMocks.findInstance(fixture.debugElement, TargetDirective).header).toBeTruthy(); + expect( + ngMocks.findInstance(fixture.debugElement, TargetComponent) + .header, + ).toBeTruthy(); + expect( + ngMocks.findInstance(fixture.debugElement, TargetDirective) + .header, + ).toBeTruthy(); }); }); @@ -55,7 +61,13 @@ describe('issue-181:mock', () => { `); - expect(ngMocks.findInstance(fixture.debugElement, TargetComponent).header).toBeTruthy(); - expect(ngMocks.findInstance(fixture.debugElement, TargetDirective).header).toBeTruthy(); + expect( + ngMocks.findInstance(fixture.debugElement, TargetComponent) + .header, + ).toBeTruthy(); + expect( + ngMocks.findInstance(fixture.debugElement, TargetDirective) + .header, + ).toBeTruthy(); }); }); diff --git a/tests/issue-197/with-providers.spec.ts b/tests/issue-197/with-providers.spec.ts index bd7c8b7956..20053e5456 100644 --- a/tests/issue-197/with-providers.spec.ts +++ b/tests/issue-197/with-providers.spec.ts @@ -1,6 +1,10 @@ import { Component, Injectable, NgModule } from '@angular/core'; import { TestBed } from '@angular/core/testing'; -import { MockBuilder, MockRender, NgModuleWithProviders } from 'ng-mocks'; +import { + MockBuilder, + MockRender, + NgModuleWithProviders, +} from 'ng-mocks'; @Injectable() class DependencyService { @@ -49,33 +53,50 @@ describe('issue-197:with-providers:manually-injection', () => { return TestBed.configureTestingModule({ declarations: module.declarations, - imports: [...(module.imports || []), DependencyModule.withProviders()], + imports: [ + ...(module.imports || []), + DependencyModule.withProviders(), + ], providers: module.providers, }).compileComponents(); }); it('creates component with provided dependencies', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toEqual('via-provider'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'via-provider', + ); }); }); describe('issue-197:with-providers:keep', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(DependencyModule.withProviders())); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule).keep( + DependencyModule.withProviders(), + ), + ); it('creates component with provided dependencies', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toEqual('via-provider'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'via-provider', + ); }); }); describe('issue-197:with-providers:mock', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).mock(DependencyModule.withProviders())); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule).mock( + DependencyModule.withProviders(), + ), + ); it('creates component with provided dependencies', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toEqual(''); + expect(fixture.nativeElement.innerHTML).toEqual( + '', + ); }); }); diff --git a/tests/issue-218/test.spec.ts b/tests/issue-218/test.spec.ts index a8bc9a33eb..ce2cfaab46 100644 --- a/tests/issue-218/test.spec.ts +++ b/tests/issue-218/test.spec.ts @@ -16,7 +16,9 @@ const TOKEN_PREFIX = new InjectionToken('PREFIX'); @Injectable() class PrefixService { - public constructor(@Inject(TOKEN_PREFIX) public readonly prefix: string) {} + public constructor( + @Inject(TOKEN_PREFIX) public readonly prefix: string, + ) {} } @Pipe({ @@ -70,7 +72,9 @@ describe('issue-218:real', () => { value: 'test', }); - expect(fixture.nativeElement.innerHTML).toContain('>real:test - real:test<'); + expect(fixture.nativeElement.innerHTML).toContain( + '>real:test - real:test<', + ); }); }); @@ -87,19 +91,27 @@ describe('issue-218:builder:mock', () => { }); describe('issue-218:builder:keep', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(TargetPipe)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule).keep(TargetPipe), + ); it('renders how we replaced it with a mock copy', () => { const fixture = MockRender(TargetComponent, { value: 'test', }); - expect(fixture.nativeElement.innerHTML).toContain('>undefined:test - undefined:test<'); + expect(fixture.nativeElement.innerHTML).toContain( + '>undefined:test - undefined:test<', + ); }); }); describe('issue-218:guts:mock', () => { - beforeEach(() => TestBed.configureTestingModule(ngMocks.guts(TargetComponent, TargetModule)).compileComponents()); + beforeEach(() => + TestBed.configureTestingModule( + ngMocks.guts(TargetComponent, TargetModule), + ).compileComponents(), + ); it('renders emptiness', () => { const fixture = MockRender(TargetComponent, { @@ -112,7 +124,9 @@ describe('issue-218:guts:mock', () => { describe('issue-218:guts:keep', () => { beforeEach(() => - TestBed.configureTestingModule(ngMocks.guts([TargetComponent, TargetPipe], TargetModule)).compileComponents(), + TestBed.configureTestingModule( + ngMocks.guts([TargetComponent, TargetPipe], TargetModule), + ).compileComponents(), ); it('renders how we replaced it with a mock copy', () => { @@ -120,6 +134,8 @@ describe('issue-218:guts:keep', () => { value: 'test', }); - expect(fixture.nativeElement.innerHTML).toContain('>undefined:test - undefined:test<'); + expect(fixture.nativeElement.innerHTML).toContain( + '>undefined:test - undefined:test<', + ); }); }); diff --git a/tests/issue-222/app-initializer.spec.ts b/tests/issue-222/app-initializer.spec.ts index 3845f23f7e..4a2932d0db 100644 --- a/tests/issue-222/app-initializer.spec.ts +++ b/tests/issue-222/app-initializer.spec.ts @@ -22,24 +22,38 @@ describe('issue-222:APP_INITIALIZER:mock', () => { it('correctly handles APP_INITIALIZER in a mock module', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain(''); + expect(fixture.nativeElement.innerHTML).toContain( + '', + ); }); }); describe('issue-222:APP_INITIALIZER:keep', () => { - beforeEach(() => MockBuilder(TargetComponent).keep(TargetModule).mock(APP_BASE_HREF, '')); + beforeEach(() => + MockBuilder(TargetComponent) + .keep(TargetModule) + .mock(APP_BASE_HREF, ''), + ); it('correctly handles APP_INITIALIZER in a kept module', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain(''); + expect(fixture.nativeElement.innerHTML).toContain( + '', + ); }); }); describe('issue-222:APP_INITIALIZER:guts', () => { - beforeEach(() => TestBed.configureTestingModule(ngMocks.guts(TargetComponent, TargetModule)).compileComponents()); + beforeEach(() => + TestBed.configureTestingModule( + ngMocks.guts(TargetComponent, TargetModule), + ).compileComponents(), + ); it('correctly handles APP_INITIALIZER in a kept module', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain(''); + expect(fixture.nativeElement.innerHTML).toContain( + '', + ); }); }); diff --git a/tests/issue-222/common-module.spec.ts b/tests/issue-222/common-module.spec.ts index 847123c2d6..938b133275 100644 --- a/tests/issue-222/common-module.spec.ts +++ b/tests/issue-222/common-module.spec.ts @@ -19,12 +19,18 @@ class TargetModule {} describe('issue-222:CommonModule', () => { beforeEach(() => TestBed.configureTestingModule({ - imports: [CommonModule, MockModule(CommonModule), MockModule(TargetModule)], + imports: [ + CommonModule, + MockModule(CommonModule), + MockModule(TargetModule), + ], }), ); it('correctly handles kept and the mock CommonModule', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toEqual(''); + expect(fixture.nativeElement.innerHTML).toEqual( + '', + ); }); }); diff --git a/tests/issue-222/dom-shared-styles-host.spec.ts b/tests/issue-222/dom-shared-styles-host.spec.ts index 04323ffd2a..7cfe6d97f1 100644 --- a/tests/issue-222/dom-shared-styles-host.spec.ts +++ b/tests/issue-222/dom-shared-styles-host.spec.ts @@ -1,4 +1,10 @@ -import { animate, state, style, transition, trigger } from '@angular/animations'; +import { + animate, + state, + style, + transition, + trigger, +} from '@angular/animations'; import { Component, NgModule } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { BrowserModule } from '@angular/platform-browser'; @@ -29,7 +35,11 @@ import { MockBuilder, MockRender, ngMocks } from 'ng-mocks'; ]), ], selector: 'target', - template: `
    The box is now {{ isOpen ? 'Open' : 'Closed' }}!
    `, + template: ` +
    + The box is now {{ isOpen ? 'Open' : 'Closed' }}! +
    + `, }) class TargetComponent { public isOpen = true; @@ -50,7 +60,9 @@ describe('issue-222:DomSharedStylesHost:mock', () => { it('correctly handles DomSharedStylesHost in a mock module', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain('The box is now Open!'); + expect(fixture.nativeElement.innerHTML).toContain( + 'The box is now Open!', + ); // Animations are replaced with a mock copy, therefore no styles. expect(fixture.nativeElement.innerHTML).not.toContain('yellow'); }); @@ -61,18 +73,26 @@ describe('issue-222:DomSharedStylesHost:keep', () => { it('correctly handles DomSharedStylesHost in a kept module', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain('The box is now Open!'); + expect(fixture.nativeElement.innerHTML).toContain( + 'The box is now Open!', + ); // Animations are kept, therefore we should get styles. expect(fixture.nativeElement.innerHTML).toContain('yellow'); }); }); describe('issue-222:DomSharedStylesHost:guts', () => { - beforeEach(() => TestBed.configureTestingModule(ngMocks.guts(TargetComponent, TargetModule)).compileComponents()); + beforeEach(() => + TestBed.configureTestingModule( + ngMocks.guts(TargetComponent, TargetModule), + ).compileComponents(), + ); it('correctly handles DomSharedStylesHost in a mock module', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain('The box is now Open!'); + expect(fixture.nativeElement.innerHTML).toContain( + 'The box is now Open!', + ); // Animations are replaced with a mock copy, therefore no styles. expect(fixture.nativeElement.innerHTML).not.toContain('yellow'); }); diff --git a/tests/issue-222/injector-scope.spec.ts b/tests/issue-222/injector-scope.spec.ts index 9a78791936..6892473c2d 100644 --- a/tests/issue-222/injector-scope.spec.ts +++ b/tests/issue-222/injector-scope.spec.ts @@ -1,4 +1,11 @@ -import { Component, Inject, Injectable as InjectableSource, NgModule, PLATFORM_ID, VERSION } from '@angular/core'; +import { + Component, + Inject, + Injectable as InjectableSource, + NgModule, + PLATFORM_ID, + VERSION, +} from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { MockBuilder, MockRender } from 'ng-mocks'; @@ -45,9 +52,12 @@ describe('issue-222:INJECTOR_SCOPE', () => { } }); - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(KeepModule)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule).keep(KeepModule), + ); it('does not mock INJECTOR_SCOPE, fails on ivy only', () => { - expect(() => MockRender(TargetComponent)).not.toThrowError(/No provider for KeepService/); + // No provider for KeepService + expect(() => MockRender(TargetComponent)).not.toThrow(); }); }); diff --git a/tests/issue-222/kept-root-injection.spec.ts b/tests/issue-222/kept-root-injection.spec.ts index ac69b926a8..eb91994a80 100644 --- a/tests/issue-222/kept-root-injection.spec.ts +++ b/tests/issue-222/kept-root-injection.spec.ts @@ -1,4 +1,9 @@ -import { Component, Injectable as InjectableSource, NgModule, VERSION } from '@angular/core'; +import { + Component, + Injectable as InjectableSource, + NgModule, + VERSION, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { MockBuilder, NG_MOCKS_ROOT_PROVIDERS } from 'ng-mocks'; @@ -57,7 +62,9 @@ describe('issue-222:kept-root-injection', () => { }); describe('real', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(KeepModule)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule).keep(KeepModule), + ); it('does not mock kept dependency', () => { const service: TargetService = TestBed.get(TargetService); @@ -66,7 +73,11 @@ describe('issue-222:kept-root-injection', () => { }); describe('NG_MOCKS_ROOT_PROVIDERS', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).mock(NG_MOCKS_ROOT_PROVIDERS).keep(KeepModule)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule) + .mock(NG_MOCKS_ROOT_PROVIDERS) + .keep(KeepModule), + ); it('does not mock kept dependency', () => { const service: TargetService = TestBed.get(TargetService); diff --git a/tests/issue-222/mock-keep-priorities.spec.ts b/tests/issue-222/mock-keep-priorities.spec.ts index ed57e76964..d83efbd00a 100644 --- a/tests/issue-222/mock-keep-priorities.spec.ts +++ b/tests/issue-222/mock-keep-priorities.spec.ts @@ -39,45 +39,72 @@ class TargetComponent {} @NgModule({ bootstrap: [TargetComponent], declarations: [TargetComponent], - imports: [BrowserModule, BrowserAnimationsModule, KeepModule, MockModule], + imports: [ + BrowserModule, + BrowserAnimationsModule, + KeepModule, + MockModule, + ], providers: [], }) export class TargetModule {} describe('issue-222:mock-keep-priorities', () => { describe('keep', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(KeepModule)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule).keep(KeepModule), + ); it('keeps all child imports', () => { const fixture = MockRender(SharedComponent); - expect(fixture.nativeElement.innerHTML).toEqual('shared'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'shared', + ); }); }); describe('mock', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(KeepModule).mock(SharedModule)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule) + .keep(KeepModule) + .mock(SharedModule), + ); it('mocks the nested module of a kept module', () => { const fixture = MockRender(SharedComponent); - expect(fixture.nativeElement.innerHTML).toEqual(''); + expect(fixture.nativeElement.innerHTML).toEqual( + '', + ); }); }); describe('reverse', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).mock(KeepModule).keep(SharedModule)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule) + .mock(KeepModule) + .keep(SharedModule), + ); it('keeps the nested module of a mock module', () => { const fixture = MockRender(SharedComponent); - expect(fixture.nativeElement.innerHTML).toEqual('shared'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'shared', + ); }); }); describe('mock keep priority', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(KeepModule).mock(MockModule)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule) + .keep(KeepModule) + .mock(MockModule), + ); it('keep wins', () => { const fixture = MockRender(SharedComponent); - expect(fixture.nativeElement.innerHTML).toEqual('shared'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'shared', + ); }); }); }); diff --git a/tests/mock-builder-by-directive/test.spec.ts b/tests/mock-builder-by-directive/test.spec.ts index 90c659f5d3..8c8b1e6ac2 100644 --- a/tests/mock-builder-by-directive/test.spec.ts +++ b/tests/mock-builder-by-directive/test.spec.ts @@ -1,4 +1,9 @@ -import { MockBuilder, MockComponent, MockRender, ngMocks } from 'ng-mocks'; +import { + MockBuilder, + MockComponent, + MockRender, + ngMocks, +} from 'ng-mocks'; import { InternalComponent } from './fixtures.components'; import { TargetModule } from './fixtures.modules'; @@ -8,7 +13,10 @@ describe('MockBuilderByDirective:real', () => { it('should render', () => { const fixture = MockRender(InternalComponent); - const element = ngMocks.find(fixture.debugElement, InternalComponent); + const element = ngMocks.find( + fixture.debugElement, + InternalComponent, + ); expect(element).toBeDefined(); }); }); @@ -18,13 +26,19 @@ describe('MockBuilderByDirective:mock', () => { it('should find mock', () => { const fixture = MockRender(InternalComponent); - const element = ngMocks.find(fixture.debugElement, MockComponent(InternalComponent)); + const element = ngMocks.find( + fixture.debugElement, + MockComponent(InternalComponent), + ); expect(element).toBeDefined(); }); it('should find original', () => { const fixture = MockRender(InternalComponent); - const element = ngMocks.find(fixture.debugElement, InternalComponent); + const element = ngMocks.find( + fixture.debugElement, + InternalComponent, + ); expect(element).toBeDefined(); }); }); diff --git a/tests/mock-builder-keeps-application-module/test.spec.ts b/tests/mock-builder-keeps-application-module/test.spec.ts index 3144d6cde8..cc461d0717 100644 --- a/tests/mock-builder-keeps-application-module/test.spec.ts +++ b/tests/mock-builder-keeps-application-module/test.spec.ts @@ -10,7 +10,10 @@ describe('MockBuilderKeepsApplicationModule:real', () => { it('should render', () => { const fixture = MockRender(TargetComponent); - const element = ngMocks.find(fixture.debugElement, TargetComponent); + const element = ngMocks.find( + fixture.debugElement, + TargetComponent, + ); expect(element).toBeDefined(); expect(TestBed.get(TARGET_TOKEN)).toBeDefined(); expect(TestBed.get(APP_INITIALIZER)).toBeDefined(); @@ -23,7 +26,10 @@ describe('MockBuilderKeepsApplicationModule:mock', () => { it('should render', () => { const fixture = MockRender(TargetComponent); - const element = ngMocks.find(fixture.debugElement, TargetComponent); + const element = ngMocks.find( + fixture.debugElement, + TargetComponent, + ); expect(element).toBeDefined(); expect(TestBed.get(TARGET_TOKEN)).toEqual(''); if (parseInt(VERSION.major, 10) < 9) { diff --git a/tests/mock-render-all-properties/test.spec.ts b/tests/mock-render-all-properties/test.spec.ts index 607c26f518..e2aab44b62 100644 --- a/tests/mock-render-all-properties/test.spec.ts +++ b/tests/mock-render-all-properties/test.spec.ts @@ -57,11 +57,14 @@ class ParentClass { @Component({ selector: 'target', template: ` - 'pubChildProp:{{ pubChildProp }}' 'pubChildPropGet:{{ pubChildPropGet }}' 'pubReadonlyChildProp:{{ - pubReadonlyChildProp - }}' 'pubReadonlyChildPropGet:{{ pubReadonlyChildPropGet }}' 'pubParentProp:{{ pubParentProp }}' 'pubParentPropGet:{{ + 'pubChildProp:{{ pubChildProp }}' 'pubChildPropGet:{{ + pubChildPropGet + }}' 'pubReadonlyChildProp:{{ pubReadonlyChildProp }}' + 'pubReadonlyChildPropGet:{{ pubReadonlyChildPropGet }}' + 'pubParentProp:{{ pubParentProp }}' 'pubParentPropGet:{{ pubParentPropGet - }}' 'pubParentParentProp:{{ pubReadonlyParentProp }}' 'pubParentParentPropGet:{{ pubReadonlyParentPropGet }}' + }}' 'pubParentParentProp:{{ pubReadonlyParentProp }}' + 'pubParentParentPropGet:{{ pubReadonlyParentPropGet }}' `, }) class TargetComponent extends ParentClass { diff --git a/tests/mock-render-mirrors-component/test.spec.ts b/tests/mock-render-mirrors-component/test.spec.ts index e6b89cc70c..7786f34370 100644 --- a/tests/mock-render-mirrors-component/test.spec.ts +++ b/tests/mock-render-mirrors-component/test.spec.ts @@ -1,6 +1,19 @@ -import { ChangeDetectorRef, Component, EventEmitter, Input, NgModule, Output } from '@angular/core'; +import { + ChangeDetectorRef, + Component, + EventEmitter, + Input, + NgModule, + Output, +} from '@angular/core'; import { ComponentFixture } from '@angular/core/testing'; -import { DefaultRenderComponent, MockBuilder, MockedComponentFixture, MockRender, ngMocks } from 'ng-mocks'; +import { + DefaultRenderComponent, + MockBuilder, + MockedComponentFixture, + MockRender, + ngMocks, +} from 'ng-mocks'; import { first } from 'rxjs/operators'; @Component({ @@ -19,7 +32,8 @@ export class TargetComponent { @Input('input') public input2: string | null = null; @Output() public output1: EventEmitter = new EventEmitter(); - @Output('output') public output2: EventEmitter = new EventEmitter(); + @Output('output') + public output2: EventEmitter = new EventEmitter(); public var1 = ''; public var2 = ''; @@ -46,12 +60,30 @@ describe('mock-render-mirrors-component', () => { it('mirrors the desired component if no params were passed', () => { const fixture = MockRender(TargetComponent); - const input1 = ngMocks.find(fixture.debugElement, '[data-role="input1"]'); - const input2 = ngMocks.find(fixture.debugElement, '[data-role="input2"]'); - const output1 = ngMocks.find(fixture.debugElement, '[data-role="output1"]'); - const output2 = ngMocks.find(fixture.debugElement, '[data-role="output2"]'); - const var1 = ngMocks.find(fixture.debugElement, '[data-role="var1"]'); - const var2 = ngMocks.find(fixture.debugElement, '[data-role="var2"]'); + const input1 = ngMocks.find( + fixture.debugElement, + '[data-role="input1"]', + ); + const input2 = ngMocks.find( + fixture.debugElement, + '[data-role="input2"]', + ); + const output1 = ngMocks.find( + fixture.debugElement, + '[data-role="output1"]', + ); + const output2 = ngMocks.find( + fixture.debugElement, + '[data-role="output2"]', + ); + const var1 = ngMocks.find( + fixture.debugElement, + '[data-role="var1"]', + ); + const var2 = ngMocks.find( + fixture.debugElement, + '[data-role="var2"]', + ); // initial state expect(input1.nativeElement.innerHTML).toEqual('input1'); @@ -77,20 +109,26 @@ describe('mock-render-mirrors-component', () => { // checking output1 let updatedOutput1 = false; - fixture.componentInstance.output1.pipe(first()).subscribe(() => (updatedOutput1 = true)); + fixture.componentInstance.output1 + .pipe(first()) + .subscribe(() => (updatedOutput1 = true)); output1.triggerEventHandler('click', null); expect(updatedOutput1).toBe(true); // checking output2 let updatedOutput2 = false; - fixture.componentInstance.output2.pipe(first()).subscribe(() => (updatedOutput2 = true)); + fixture.componentInstance.output2 + .pipe(first()) + .subscribe(() => (updatedOutput2 = true)); output2.triggerEventHandler('click', null); expect(updatedOutput2).toBe(true); }); it('correctly inherits types', () => { // keeps the 2nd args as DefaultRenderComponent - const fixture1: MockedComponentFixture = MockRender(TargetComponent); + const fixture1: MockedComponentFixture = MockRender( + TargetComponent, + ); fixture1.componentInstance.input1 = '1'; fixture1.detectChanges(); expect(fixture1).toBeDefined(); @@ -99,26 +137,30 @@ describe('mock-render-mirrors-component', () => { // we have to provide DefaultRenderComponent in this case. // the generated component isn't the same as the testing component. - const fixture2: ComponentFixture> = MockRender(TargetComponent); + const fixture2: ComponentFixture< + DefaultRenderComponent + > = MockRender(TargetComponent); fixture2.componentInstance.input1 = '1'; fixture2.detectChanges(); expect(fixture2).toBeDefined(); expect(fixture2.componentInstance.input1).toBe('1'); // full declaration of the mock fixture type. - const fixture3: MockedComponentFixture> = MockRender( + const fixture3: MockedComponentFixture< TargetComponent, - { - input1: '1', - input3: '3', - }, - ); + Record<'input1' | 'input3', string> + > = MockRender(TargetComponent, { + input1: '1', + input3: '3', + }); expect(fixture3).toBeDefined(); expect(fixture3.componentInstance.input3).toBe('3'); expect(fixture3.point.componentInstance.input1).toBe('1'); // full declaration of the default fixture type. - const fixture4: ComponentFixture> = MockRender(TargetComponent, { + const fixture4: ComponentFixture< + Record<'input1' | 'input3', string> + > = MockRender(TargetComponent, { input1: '1', input3: '3', }); diff --git a/tests/module-with-factory-tokens/test.spec.ts b/tests/module-with-factory-tokens/test.spec.ts index 8a0aaec427..ecf31c2eb3 100644 --- a/tests/module-with-factory-tokens/test.spec.ts +++ b/tests/module-with-factory-tokens/test.spec.ts @@ -1,12 +1,22 @@ import { VERSION } from '@angular/core'; import { MockBuilder, MockRender } from 'ng-mocks'; -import { MY_TOKEN_MULTI, MY_TOKEN_SINGLE, TargetComponent, TargetModule } from './fixtures'; +import { + MY_TOKEN_MULTI, + MY_TOKEN_SINGLE, + TargetComponent, + TargetModule, +} from './fixtures'; // Because all tokens have factories the test should render them correctly. // There's no way to specify multi in a factory, so we don't get an array. describe('module-with-factory-tokens:real', () => { - beforeEach(() => MockBuilder().keep(TargetModule).keep(MY_TOKEN_SINGLE).keep(MY_TOKEN_MULTI)); + beforeEach(() => + MockBuilder() + .keep(TargetModule) + .keep(MY_TOKEN_SINGLE) + .keep(MY_TOKEN_MULTI), + ); it('renders all tokens', () => { if (parseInt(VERSION.major, 10) <= 5) { @@ -25,7 +35,11 @@ describe('module-with-factory-tokens:real', () => { // Because all tokens are kept the test should render them correctly. // There's no way to specify multi in a factory, so we don't get an array. describe('module-with-factory-tokens:keep', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(MY_TOKEN_SINGLE).keep(MY_TOKEN_MULTI)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule) + .keep(MY_TOKEN_SINGLE) + .keep(MY_TOKEN_MULTI), + ); it('renders all tokens', () => { if (parseInt(VERSION.major, 10) <= 5) { @@ -59,7 +73,9 @@ describe('module-with-factory-tokens:mock-0', () => { it('fails to render all tokens', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).toContain('"V1" [ "V2" ]'); + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toContain('"V1" [ "V2" ]'); }); }); @@ -67,11 +83,17 @@ describe('module-with-factory-tokens:mock-0', () => { // The tokens will be added to provides with undefined values. // Result of the render is an empty string because there's no way to pass multi. describe('module-with-factory-tokens:mock-1', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).mock(MY_TOKEN_SINGLE).mock(MY_TOKEN_MULTI)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule) + .mock(MY_TOKEN_SINGLE) + .mock(MY_TOKEN_MULTI), + ); it('renders all tokens', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).toEqual(' '); + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toEqual(' '); }); }); @@ -99,7 +121,11 @@ describe('module-with-factory-tokens:mock-2', () => { // UPD 2020-10-28: it has been fixed. Now all missed tokens are added to the TestModuleMeta, // therefore we have to keep them. describe('module-with-factory-tokens:mock-3', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(MY_TOKEN_SINGLE).keep(MY_TOKEN_MULTI)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule) + .keep(MY_TOKEN_SINGLE) + .keep(MY_TOKEN_MULTI), + ); it('renders all tokens', () => { if (parseInt(VERSION.major, 10) <= 5) { diff --git a/tests/module-with-tokens/test.spec.ts b/tests/module-with-tokens/test.spec.ts index a502ed1d81..2859d0183c 100644 --- a/tests/module-with-tokens/test.spec.ts +++ b/tests/module-with-tokens/test.spec.ts @@ -1,6 +1,11 @@ import { MockBuilder, MockRender } from 'ng-mocks'; -import { MY_TOKEN_MULTI, MY_TOKEN_SINGLE, TargetComponent, TargetModule } from './fixtures'; +import { + MY_TOKEN_MULTI, + MY_TOKEN_SINGLE, + TargetComponent, + TargetModule, +} from './fixtures'; // Preferred way. // Because tokens are provided in the testbed module with custom values the test should render them. @@ -25,7 +30,9 @@ describe('module-with-tokens:mock-0', () => { it('fails to render all tokens', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).toEqual( + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toEqual( '"V1" [ "V2", "V3" ]', ); }); @@ -34,11 +41,17 @@ describe('module-with-tokens:mock-0', () => { // Because all tokens are replaced with mock copies in the module the test should render empty values. // interesting is that for multi it's null, not undefined. describe('module-with-tokens:mock-1', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).mock(MY_TOKEN_SINGLE).mock(MY_TOKEN_MULTI)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule) + .mock(MY_TOKEN_SINGLE) + .mock(MY_TOKEN_MULTI), + ); it('renders all tokens', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).toEqual( + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toEqual( ' [ null, null ]', ); }); @@ -54,7 +67,9 @@ describe('module-with-tokens:mock-2', () => { it('renders all tokens', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).toEqual( + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toEqual( '' + '"MOCK_MY_TOKEN_SINGLE" [ "MOCK_MY_TOKEN_MULTI", "MOCK_MY_TOKEN_MULTI" ]' + '', @@ -71,7 +86,8 @@ describe('module-with-tokens:mock-3', () => { beforeEach(() => MockBuilder(TargetComponent, TargetModule)); it('does not fail to render all tokens', () => { - expect(() => MockRender(TargetComponent)).not.toThrowError(/InjectionToken/); + // InjectionToken + expect(() => MockRender(TargetComponent)).not.toThrow(); }); it('renders mock tokens with respect of multi flag', () => { @@ -88,7 +104,9 @@ describe('module-with-tokens:real', () => { it('renders all tokens', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).toEqual( + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toEqual( '"MY_TOKEN_SINGLE" [ "MY_TOKEN_MULTI", "MY_TOKEN_MULTI_2" ]', ); }); @@ -96,11 +114,17 @@ describe('module-with-tokens:real', () => { // Because all tokens are kept in the module the test should render them correctly. describe('module-with-tokens:keep', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(MY_TOKEN_SINGLE).keep(MY_TOKEN_MULTI)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule) + .keep(MY_TOKEN_SINGLE) + .keep(MY_TOKEN_MULTI), + ); it('renders all tokens', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).toEqual( + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toEqual( '"MY_TOKEN_SINGLE" [ "MY_TOKEN_MULTI", "MY_TOKEN_MULTI_2" ]', ); }); diff --git a/tests/multi-tokens/test.spec.ts b/tests/multi-tokens/test.spec.ts index d348f03143..6beb0ec969 100644 --- a/tests/multi-tokens/test.spec.ts +++ b/tests/multi-tokens/test.spec.ts @@ -1,4 +1,9 @@ -import { Inject, Injectable, InjectionToken, NgModule } from '@angular/core'; +import { + Inject, + Injectable, + InjectionToken, + NgModule, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { getInjection, MockBuilder } from 'ng-mocks'; @@ -6,7 +11,9 @@ const TARGET_TOKEN = new InjectionToken('MY_TOKEN_SINGLE'); @Injectable() class TargetService { - public constructor(@Inject(TARGET_TOKEN) public readonly tokens: string[]) {} + public constructor( + @Inject(TARGET_TOKEN) public readonly tokens: string[], + ) {} } @NgModule({ diff --git a/tests/ng-mocks-search-with-no-fixture/fixtures.ts b/tests/ng-mocks-search-with-no-fixture/fixtures.ts new file mode 100644 index 0000000000..5601fd49ae --- /dev/null +++ b/tests/ng-mocks-search-with-no-fixture/fixtures.ts @@ -0,0 +1,26 @@ +import { Component, Input, NgModule } from '@angular/core'; + +@Component({ + selector: 'target', + template: `{{ target }}`, +}) +export class TargetComponent { + @Input() public readonly target = ''; +} + +@Component({ + selector: 'missed', + template: `missed`, +}) +export class MissedComponent {} + +@Component({ + selector: 'test', + template: ``, +}) +export class TestComponent {} + +@NgModule({ + declarations: [TargetComponent, MissedComponent, TestComponent], +}) +export class TargetModule {} diff --git a/tests/ng-mocks-search-with-no-fixture/test.fixture.spec.ts b/tests/ng-mocks-search-with-no-fixture/test.fixture.spec.ts new file mode 100644 index 0000000000..67c70c5f81 --- /dev/null +++ b/tests/ng-mocks-search-with-no-fixture/test.fixture.spec.ts @@ -0,0 +1,333 @@ +// tslint:disable max-file-line-count + +import { + isMockOf, + MockBuilder, + MockedComponentFixture, + MockRender, + ngMocks, +} from 'ng-mocks'; + +import { + MissedComponent, + TargetComponent, + TargetModule, + TestComponent, +} from './fixtures'; + +describe('ng-mocks-search-with-no-fixture:fixture', () => { + ngMocks.faster(); + + let fixture: MockedComponentFixture; + beforeEach(() => MockBuilder(TestComponent, TargetModule)); + beforeEach(() => (fixture = MockRender(TestComponent))); + + describe('empty', () => { + it('.find type', () => { + const element = ngMocks.find(TargetComponent); + expect( + isMockOf(element.componentInstance, TargetComponent), + ).toBeTruthy(); + expect(element.componentInstance.target).toEqual('1'); + + expect( + ngMocks.find(MissedComponent, undefined), + ).toBeUndefined(); + expect(() => ngMocks.find(MissedComponent)).toThrowError( + /Cannot find an element via ngMocks.find\(MissedComponent\)/, + ); + }); + + it('.find css selector', () => { + const element = ngMocks.find('target'); + expect( + isMockOf(element.componentInstance, TargetComponent), + ).toBeTruthy(); + expect(element.componentInstance.target).toEqual('1'); + + expect( + ngMocks.find('missed', undefined), + ).toBeUndefined(); + expect(() => + ngMocks.find('missed'), + ).toThrowError( + /Cannot find an element via ngMocks.find\(missed\)/, + ); + }); + + it('.findAll type', () => { + const elements = ngMocks.findAll(TargetComponent); + expect( + isMockOf(elements[0].componentInstance, TargetComponent), + ).toBeTruthy(); + expect(elements[0].componentInstance.target).toEqual('1'); + expect( + isMockOf(elements[1].componentInstance, TargetComponent), + ).toBeTruthy(); + expect(elements[1].componentInstance.target).toEqual('2'); + }); + + it('.findAll css selector', () => { + const elements = ngMocks.findAll('target'); + expect( + isMockOf(elements[0].componentInstance, TargetComponent), + ).toBeTruthy(); + expect(elements[0].componentInstance.target).toEqual('1'); + expect( + isMockOf(elements[1].componentInstance, TargetComponent), + ).toBeTruthy(); + expect(elements[1].componentInstance.target).toEqual('2'); + }); + + it('.findInstance', () => { + const componentInstance = ngMocks.findInstance(TargetComponent); + expect( + isMockOf(componentInstance, TargetComponent), + ).toBeTruthy(); + expect(componentInstance.target).toEqual('1'); + + expect( + ngMocks.findInstance(MissedComponent, undefined), + ).toBeUndefined(); + expect(() => + ngMocks.findInstance(MissedComponent), + ).toThrowError( + /Cannot find an instance via ngMocks.findInstance\(MissedComponent\)/, + ); + }); + + it('.findInstances', () => { + const componentInstances = ngMocks.findInstances( + TargetComponent, + ); + expect( + isMockOf(componentInstances[0], TargetComponent), + ).toBeTruthy(); + expect(componentInstances[0].target).toEqual('1'); + expect( + isMockOf(componentInstances[1], TargetComponent), + ).toBeTruthy(); + expect(componentInstances[1].target).toEqual('2'); + }); + }); + + describe('fixture', () => { + it('.find type', () => { + const element = ngMocks.find(fixture, TargetComponent); + expect( + isMockOf(element.componentInstance, TargetComponent), + ).toBeTruthy(); + expect(element.componentInstance.target).toEqual('1'); + + expect( + ngMocks.find(fixture, MissedComponent, undefined), + ).toBeUndefined(); + expect(() => + ngMocks.find(fixture, MissedComponent), + ).toThrowError( + /Cannot find an element via ngMocks.find\(MissedComponent\)/, + ); + }); + + it('.find css selector', () => { + const element = ngMocks.find( + fixture, + 'target', + ); + expect( + isMockOf(element.componentInstance, TargetComponent), + ).toBeTruthy(); + expect(element.componentInstance.target).toEqual('1'); + + expect( + ngMocks.find(fixture, 'missed', undefined), + ).toBeUndefined(); + expect(() => + ngMocks.find(fixture, 'missed'), + ).toThrowError( + /Cannot find an element via ngMocks.find\(missed\)/, + ); + }); + + it('.findAll type', () => { + const elements = ngMocks.findAll(fixture, TargetComponent); + expect( + isMockOf(elements[0].componentInstance, TargetComponent), + ).toBeTruthy(); + expect(elements[0].componentInstance.target).toEqual('1'); + expect( + isMockOf(elements[1].componentInstance, TargetComponent), + ).toBeTruthy(); + expect(elements[1].componentInstance.target).toEqual('2'); + }); + + it('.findAll css selector', () => { + const elements = ngMocks.findAll( + fixture, + 'target', + ); + expect( + isMockOf(elements[0].componentInstance, TargetComponent), + ).toBeTruthy(); + expect(elements[0].componentInstance.target).toEqual('1'); + expect( + isMockOf(elements[1].componentInstance, TargetComponent), + ).toBeTruthy(); + expect(elements[1].componentInstance.target).toEqual('2'); + }); + + it('.findInstance', () => { + const componentInstance = ngMocks.findInstance( + fixture, + TargetComponent, + ); + expect( + isMockOf(componentInstance, TargetComponent), + ).toBeTruthy(); + expect(componentInstance.target).toEqual('1'); + + expect( + ngMocks.findInstance(fixture, MissedComponent, undefined), + ).toBeUndefined(); + expect(() => + ngMocks.findInstance(fixture, MissedComponent), + ).toThrowError( + /Cannot find an instance via ngMocks.findInstance\(MissedComponent\)/, + ); + }); + + it('.findInstances', () => { + const componentInstances = ngMocks.findInstances( + fixture, + TargetComponent, + ); + expect( + isMockOf(componentInstances[0], TargetComponent), + ).toBeTruthy(); + expect(componentInstances[0].target).toEqual('1'); + expect( + isMockOf(componentInstances[1], TargetComponent), + ).toBeTruthy(); + expect(componentInstances[1].target).toEqual('2'); + }); + }); + + describe('debugElement', () => { + it('.find type', () => { + const element = ngMocks.find( + fixture.debugElement, + TargetComponent, + ); + expect( + isMockOf(element.componentInstance, TargetComponent), + ).toBeTruthy(); + expect(element.componentInstance.target).toEqual('1'); + + expect( + ngMocks.find( + fixture.debugElement, + MissedComponent, + undefined, + ), + ).toBeUndefined(); + expect(() => + ngMocks.find(fixture.debugElement, MissedComponent), + ).toThrowError( + /Cannot find an element via ngMocks.find\(MissedComponent\)/, + ); + }); + + it('.find css selector', () => { + const element = ngMocks.find( + fixture.debugElement, + 'target', + ); + expect( + isMockOf(element.componentInstance, TargetComponent), + ).toBeTruthy(); + expect(element.componentInstance.target).toEqual('1'); + + expect( + ngMocks.find( + fixture.debugElement, + 'missed', + undefined, + ), + ).toBeUndefined(); + expect(() => + ngMocks.find(fixture.debugElement, 'missed'), + ).toThrowError( + /Cannot find an element via ngMocks.find\(missed\)/, + ); + }); + + it('.findAll type', () => { + const elements = ngMocks.findAll( + fixture.debugElement, + TargetComponent, + ); + expect( + isMockOf(elements[0].componentInstance, TargetComponent), + ).toBeTruthy(); + expect(elements[0].componentInstance.target).toEqual('1'); + expect( + isMockOf(elements[1].componentInstance, TargetComponent), + ).toBeTruthy(); + expect(elements[1].componentInstance.target).toEqual('2'); + }); + + it('.findAll css selector', () => { + const elements = ngMocks.findAll( + fixture.debugElement, + 'target', + ); + expect( + isMockOf(elements[0].componentInstance, TargetComponent), + ).toBeTruthy(); + expect(elements[0].componentInstance.target).toEqual('1'); + expect( + isMockOf(elements[1].componentInstance, TargetComponent), + ).toBeTruthy(); + expect(elements[1].componentInstance.target).toEqual('2'); + }); + + it('.findInstance', () => { + const componentInstance = ngMocks.findInstance( + fixture.debugElement, + TargetComponent, + ); + expect( + isMockOf(componentInstance, TargetComponent), + ).toBeTruthy(); + expect(componentInstance.target).toEqual('1'); + + expect( + ngMocks.findInstance( + fixture.debugElement, + MissedComponent, + undefined, + ), + ).toBeUndefined(); + expect(() => + ngMocks.findInstance(fixture.debugElement, MissedComponent), + ).toThrowError( + /Cannot find an instance via ngMocks.findInstance\(MissedComponent\)/, + ); + }); + + it('.findInstances', () => { + const componentInstances = ngMocks.findInstances( + fixture.debugElement, + TargetComponent, + ); + expect( + isMockOf(componentInstances[0], TargetComponent), + ).toBeTruthy(); + expect(componentInstances[0].target).toEqual('1'); + expect( + isMockOf(componentInstances[1], TargetComponent), + ).toBeTruthy(); + expect(componentInstances[1].target).toEqual('2'); + }); + }); +}); diff --git a/tests/ng-mocks-search-with-no-fixture/test.no-fixture.spec.ts b/tests/ng-mocks-search-with-no-fixture/test.no-fixture.spec.ts new file mode 100644 index 0000000000..3ed658a9e9 --- /dev/null +++ b/tests/ng-mocks-search-with-no-fixture/test.no-fixture.spec.ts @@ -0,0 +1,43 @@ +import { ngMocks } from 'ng-mocks'; + +import { TargetComponent } from './fixtures'; + +describe('ng-mocks-search-with-no-fixture:no-fixture', () => { + it('.find type', () => { + expect(() => ngMocks.find(TargetComponent)).toThrowError( + /Cannot find an element via ngMocks.find\(TargetComponent\)/, + ); + expect(ngMocks.find(TargetComponent, undefined)).toBeUndefined(); + }); + + it('.find css selector', () => { + expect(() => ngMocks.find('target')).toThrowError( + /Cannot find an element via ngMocks.find\(target\)/, + ); + expect(ngMocks.find('target', undefined)).toBeUndefined(); + }); + + it('.findAll type', () => { + const elements = ngMocks.findAll(TargetComponent); + expect(elements.length).toEqual(0); + }); + + it('.findAll css selector', () => { + const elements = ngMocks.findAll('target'); + expect(elements.length).toEqual(0); + }); + + it('.findInstance', () => { + expect(() => ngMocks.findInstance(TargetComponent)).toThrowError( + /Cannot find an instance via ngMocks.findInstance\(TargetComponent\)/, + ); + expect( + ngMocks.findInstance(TargetComponent, undefined), + ).toBeUndefined(); + }); + + it('.findInstances', () => { + const componentInstances = ngMocks.findInstances(TargetComponent); + expect(componentInstances.length).toEqual(0); + }); +}); diff --git a/tests/ng-mocks-search-with-no-fixture/test.spec.ts b/tests/ng-mocks-search-with-no-fixture/test.spec.ts deleted file mode 100644 index 1efe529262..0000000000 --- a/tests/ng-mocks-search-with-no-fixture/test.spec.ts +++ /dev/null @@ -1,248 +0,0 @@ -import { Component, Input, NgModule } from '@angular/core'; -import { isMockOf, MockBuilder, MockedComponentFixture, MockRender, ngMocks } from 'ng-mocks'; - -@Component({ - selector: 'target', - template: `{{ target }}`, -}) -class TargetComponent { - @Input() public readonly target = ''; -} - -@Component({ - selector: 'missed', - template: `missed`, -}) -class MissedComponent {} - -@Component({ - selector: 'test', - template: ``, -}) -class TestComponent {} - -@NgModule({ - declarations: [TargetComponent, MissedComponent, TestComponent], -}) -class TargetModule {} - -describe('ng-mocks-search-with-no-fixture:no-fixture', () => { - it('.find type', () => { - expect(() => ngMocks.find(TargetComponent)).toThrowError( - /Cannot find an element via ngMocks.find\(TargetComponent\)/, - ); - expect(ngMocks.find(TargetComponent, undefined)).toBeUndefined(); - }); - - it('.find css selector', () => { - expect(() => ngMocks.find('target')).toThrowError(/Cannot find an element via ngMocks.find\(target\)/); - expect(ngMocks.find('target', undefined)).toBeUndefined(); - }); - - it('.findAll type', () => { - const elements = ngMocks.findAll(TargetComponent); - expect(elements.length).toEqual(0); - }); - - it('.findAll css selector', () => { - const elements = ngMocks.findAll('target'); - expect(elements.length).toEqual(0); - }); - - it('.findInstance', () => { - expect(() => ngMocks.findInstance(TargetComponent)).toThrowError( - /Cannot find an instance via ngMocks.findInstance\(TargetComponent\)/, - ); - expect(ngMocks.findInstance(TargetComponent, undefined)).toBeUndefined(); - }); - - it('.findInstances', () => { - const componentInstances = ngMocks.findInstances(TargetComponent); - expect(componentInstances.length).toEqual(0); - }); -}); - -describe('ng-mocks-search-with-no-fixture:fixture', () => { - ngMocks.faster(); - - let fixture: MockedComponentFixture; - beforeEach(() => MockBuilder(TestComponent, TargetModule)); - beforeEach(() => (fixture = MockRender(TestComponent))); - - describe('empty', () => { - it('.find type', () => { - const element = ngMocks.find(TargetComponent); - expect(isMockOf(element.componentInstance, TargetComponent)).toBeTruthy(); - expect(element.componentInstance.target).toEqual('1'); - - expect(ngMocks.find(MissedComponent, undefined)).toBeUndefined(); - expect(() => ngMocks.find(MissedComponent)).toThrowError( - /Cannot find an element via ngMocks.find\(MissedComponent\)/, - ); - }); - - it('.find css selector', () => { - const element = ngMocks.find('target'); - expect(isMockOf(element.componentInstance, TargetComponent)).toBeTruthy(); - expect(element.componentInstance.target).toEqual('1'); - - expect(ngMocks.find('missed', undefined)).toBeUndefined(); - expect(() => ngMocks.find('missed')).toThrowError( - /Cannot find an element via ngMocks.find\(missed\)/, - ); - }); - - it('.findAll type', () => { - const elements = ngMocks.findAll(TargetComponent); - expect(isMockOf(elements[0].componentInstance, TargetComponent)).toBeTruthy(); - expect(elements[0].componentInstance.target).toEqual('1'); - expect(isMockOf(elements[1].componentInstance, TargetComponent)).toBeTruthy(); - expect(elements[1].componentInstance.target).toEqual('2'); - }); - - it('.findAll css selector', () => { - const elements = ngMocks.findAll('target'); - expect(isMockOf(elements[0].componentInstance, TargetComponent)).toBeTruthy(); - expect(elements[0].componentInstance.target).toEqual('1'); - expect(isMockOf(elements[1].componentInstance, TargetComponent)).toBeTruthy(); - expect(elements[1].componentInstance.target).toEqual('2'); - }); - - it('.findInstance', () => { - const componentInstance = ngMocks.findInstance(TargetComponent); - expect(isMockOf(componentInstance, TargetComponent)).toBeTruthy(); - expect(componentInstance.target).toEqual('1'); - - expect(ngMocks.findInstance(MissedComponent, undefined)).toBeUndefined(); - expect(() => ngMocks.findInstance(MissedComponent)).toThrowError( - /Cannot find an instance via ngMocks.findInstance\(MissedComponent\)/, - ); - }); - - it('.findInstances', () => { - const componentInstances = ngMocks.findInstances(TargetComponent); - expect(isMockOf(componentInstances[0], TargetComponent)).toBeTruthy(); - expect(componentInstances[0].target).toEqual('1'); - expect(isMockOf(componentInstances[1], TargetComponent)).toBeTruthy(); - expect(componentInstances[1].target).toEqual('2'); - }); - }); - - describe('fixture', () => { - it('.find type', () => { - const element = ngMocks.find(fixture, TargetComponent); - expect(isMockOf(element.componentInstance, TargetComponent)).toBeTruthy(); - expect(element.componentInstance.target).toEqual('1'); - - expect(ngMocks.find(fixture, MissedComponent, undefined)).toBeUndefined(); - expect(() => ngMocks.find(fixture, MissedComponent)).toThrowError( - /Cannot find an element via ngMocks.find\(MissedComponent\)/, - ); - }); - - it('.find css selector', () => { - const element = ngMocks.find(fixture, 'target'); - expect(isMockOf(element.componentInstance, TargetComponent)).toBeTruthy(); - expect(element.componentInstance.target).toEqual('1'); - - expect(ngMocks.find(fixture, 'missed', undefined)).toBeUndefined(); - expect(() => ngMocks.find(fixture, 'missed')).toThrowError( - /Cannot find an element via ngMocks.find\(missed\)/, - ); - }); - - it('.findAll type', () => { - const elements = ngMocks.findAll(fixture, TargetComponent); - expect(isMockOf(elements[0].componentInstance, TargetComponent)).toBeTruthy(); - expect(elements[0].componentInstance.target).toEqual('1'); - expect(isMockOf(elements[1].componentInstance, TargetComponent)).toBeTruthy(); - expect(elements[1].componentInstance.target).toEqual('2'); - }); - - it('.findAll css selector', () => { - const elements = ngMocks.findAll(fixture, 'target'); - expect(isMockOf(elements[0].componentInstance, TargetComponent)).toBeTruthy(); - expect(elements[0].componentInstance.target).toEqual('1'); - expect(isMockOf(elements[1].componentInstance, TargetComponent)).toBeTruthy(); - expect(elements[1].componentInstance.target).toEqual('2'); - }); - - it('.findInstance', () => { - const componentInstance = ngMocks.findInstance(fixture, TargetComponent); - expect(isMockOf(componentInstance, TargetComponent)).toBeTruthy(); - expect(componentInstance.target).toEqual('1'); - - expect(ngMocks.findInstance(fixture, MissedComponent, undefined)).toBeUndefined(); - expect(() => ngMocks.findInstance(fixture, MissedComponent)).toThrowError( - /Cannot find an instance via ngMocks.findInstance\(MissedComponent\)/, - ); - }); - - it('.findInstances', () => { - const componentInstances = ngMocks.findInstances(fixture, TargetComponent); - expect(isMockOf(componentInstances[0], TargetComponent)).toBeTruthy(); - expect(componentInstances[0].target).toEqual('1'); - expect(isMockOf(componentInstances[1], TargetComponent)).toBeTruthy(); - expect(componentInstances[1].target).toEqual('2'); - }); - }); - - describe('debugElement', () => { - it('.find type', () => { - const element = ngMocks.find(fixture.debugElement, TargetComponent); - expect(isMockOf(element.componentInstance, TargetComponent)).toBeTruthy(); - expect(element.componentInstance.target).toEqual('1'); - - expect(ngMocks.find(fixture.debugElement, MissedComponent, undefined)).toBeUndefined(); - expect(() => ngMocks.find(fixture.debugElement, MissedComponent)).toThrowError( - /Cannot find an element via ngMocks.find\(MissedComponent\)/, - ); - }); - - it('.find css selector', () => { - const element = ngMocks.find(fixture.debugElement, 'target'); - expect(isMockOf(element.componentInstance, TargetComponent)).toBeTruthy(); - expect(element.componentInstance.target).toEqual('1'); - - expect(ngMocks.find(fixture.debugElement, 'missed', undefined)).toBeUndefined(); - expect(() => ngMocks.find(fixture.debugElement, 'missed')).toThrowError( - /Cannot find an element via ngMocks.find\(missed\)/, - ); - }); - - it('.findAll type', () => { - const elements = ngMocks.findAll(fixture.debugElement, TargetComponent); - expect(isMockOf(elements[0].componentInstance, TargetComponent)).toBeTruthy(); - expect(elements[0].componentInstance.target).toEqual('1'); - expect(isMockOf(elements[1].componentInstance, TargetComponent)).toBeTruthy(); - expect(elements[1].componentInstance.target).toEqual('2'); - }); - - it('.findAll css selector', () => { - const elements = ngMocks.findAll(fixture.debugElement, 'target'); - expect(isMockOf(elements[0].componentInstance, TargetComponent)).toBeTruthy(); - expect(elements[0].componentInstance.target).toEqual('1'); - expect(isMockOf(elements[1].componentInstance, TargetComponent)).toBeTruthy(); - expect(elements[1].componentInstance.target).toEqual('2'); - }); - - it('.findInstance', () => { - const componentInstance = ngMocks.findInstance(fixture.debugElement, TargetComponent); - expect(isMockOf(componentInstance, TargetComponent)).toBeTruthy(); - expect(componentInstance.target).toEqual('1'); - - expect(ngMocks.findInstance(fixture.debugElement, MissedComponent, undefined)).toBeUndefined(); - expect(() => ngMocks.findInstance(fixture.debugElement, MissedComponent)).toThrowError( - /Cannot find an instance via ngMocks.findInstance\(MissedComponent\)/, - ); - }); - - it('.findInstances', () => { - const componentInstances = ngMocks.findInstances(fixture.debugElement, TargetComponent); - expect(isMockOf(componentInstances[0], TargetComponent)).toBeTruthy(); - expect(componentInstances[0].target).toEqual('1'); - expect(isMockOf(componentInstances[1], TargetComponent)).toBeTruthy(); - expect(componentInstances[1].target).toEqual('2'); - }); - }); -}); diff --git a/tests/normal-usage-after-mock-builder/test.spec.ts b/tests/normal-usage-after-mock-builder/test.spec.ts index f921a909ca..024baefa49 100644 --- a/tests/normal-usage-after-mock-builder/test.spec.ts +++ b/tests/normal-usage-after-mock-builder/test.spec.ts @@ -1,6 +1,10 @@ import { MockBuilder, MockRender } from 'ng-mocks'; -import { FakeComponent, RealComponent, TargetComponent } from './fixtures.components'; +import { + FakeComponent, + RealComponent, + TargetComponent, +} from './fixtures.components'; import { TargetModule } from './fixtures.modules'; describe('normal-usage-after-mock-builder:real1', () => { @@ -8,16 +12,24 @@ describe('normal-usage-after-mock-builder:real1', () => { it('renders real component because we did not use MockBuilder.replace yet', () => { const fixture = MockRender(TargetComponent); - expect(fixture.debugElement.nativeElement.innerHTML).toEqual('real1'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'real1', + ); }); }); describe('normal-usage-after-mock-builder:mock', () => { - beforeEach(() => MockBuilder().keep(TargetModule).replace(RealComponent, FakeComponent, { dependency: true })); + beforeEach(() => + MockBuilder() + .keep(TargetModule) + .replace(RealComponent, FakeComponent, { dependency: true }), + ); it('renders fake component because we used MockBuilder.replace', () => { const fixture = MockRender(TargetComponent); - expect(fixture.debugElement.nativeElement.innerHTML).toEqual('fake1'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'fake1', + ); }); }); @@ -26,6 +38,8 @@ describe('normal-usage-after-mock-builder:real2', () => { it('has to render real component after MockBuilder.replace', () => { const fixture = MockRender(TargetComponent); - expect(fixture.debugElement.nativeElement.innerHTML).toEqual('real1'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'real1', + ); }); }); diff --git a/tests/on-push/on-push.spec.ts b/tests/on-push/on-push.spec.ts index 3e7ca83bba..2f080262dc 100644 --- a/tests/on-push/on-push.spec.ts +++ b/tests/on-push/on-push.spec.ts @@ -1,4 +1,8 @@ -import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; +import { + ChangeDetectionStrategy, + Component, + Input, +} from '@angular/core'; import { MockBuilder, MockRender } from 'ng-mocks'; @Component({ diff --git a/tests/performance/test.spec.ts b/tests/performance/test.spec.ts index 7f1487692d..d67c8fe0a8 100644 --- a/tests/performance/test.spec.ts +++ b/tests/performance/test.spec.ts @@ -30,7 +30,9 @@ describe('performance:correct', () => { beforeAll(() => { backupWarn = console.warn; - console.warn = jasmine.createSpy('console').and.callFake(console.log); + console.warn = jasmine + .createSpy('console') + .and.callFake(console.log); }); afterAll(() => { @@ -39,7 +41,9 @@ describe('performance:correct', () => { ngMocks.faster(); - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(TargetService)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule).keep(TargetService), + ); it('creates a module on first call', () => { expect(console.warn).not.toHaveBeenCalled(); @@ -76,6 +80,8 @@ describe('performance:wrong', () => { }); it('reuses a module on second call', () => { - expect(console.warn).toHaveBeenCalledWith(jasmine.stringMatching(/ngMocks.faster/)); + expect(console.warn).toHaveBeenCalledWith( + jasmine.stringMatching(/ngMocks.faster/), + ); }); }); diff --git a/tests/pipe-as-service/test.spec.ts b/tests/pipe-as-service/test.spec.ts index c9a6e7158f..784b3c37c4 100644 --- a/tests/pipe-as-service/test.spec.ts +++ b/tests/pipe-as-service/test.spec.ts @@ -1,6 +1,18 @@ -import { Component, Injectable, NgModule, Pipe, PipeTransform } from '@angular/core'; +import { + Component, + Injectable, + NgModule, + Pipe, + PipeTransform, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; -import { MockBuilder, MockInstance, MockRender, MockReset, ngMocks } from 'ng-mocks'; +import { + MockBuilder, + MockInstance, + MockRender, + MockReset, + ngMocks, +} from 'ng-mocks'; @Pipe({ name: 'target', @@ -21,9 +33,9 @@ class TargetPipe implements PipeTransform { @Component({ selector: 'target', template: ` - 'pipe:{{ '123' | target }}' 's:transform:{{ service.transform('123') }}' 's:name:{{ service.name }}' 's:echo:{{ - service.echo() - }}' + 'pipe:{{ '123' | target }}' 's:transform:{{ + service.transform('123') + }}' 's:name:{{ service.name }}' 's:echo:{{ service.echo() }}' `, }) class TargetComponent { @@ -39,33 +51,55 @@ class TargetModule {} describe('pipe-as-service', () => { describe('default', () => { - beforeEach(() => TestBed.configureTestingModule({ imports: [TargetModule] }).compileComponents()); + beforeEach(() => + TestBed.configureTestingModule({ + imports: [TargetModule], + }).compileComponents(), + ); it('renders correctly', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain(`'pipe:["123"]'`); - expect(fixture.nativeElement.innerHTML).toContain(`'s:transform:["123"]'`); - expect(fixture.nativeElement.innerHTML).toContain(`'s:name:target'`); - expect(fixture.nativeElement.innerHTML).toContain(`'s:echo:target'`); + expect(fixture.nativeElement.innerHTML).toContain( + `'pipe:["123"]'`, + ); + expect(fixture.nativeElement.innerHTML).toContain( + `'s:transform:["123"]'`, + ); + expect(fixture.nativeElement.innerHTML).toContain( + `'s:name:target'`, + ); + expect(fixture.nativeElement.innerHTML).toContain( + `'s:echo:target'`, + ); }); }); describe('guts', () => { - beforeEach(() => TestBed.configureTestingModule(ngMocks.guts(TargetComponent, TargetModule))); + beforeEach(() => + TestBed.configureTestingModule( + ngMocks.guts(TargetComponent, TargetModule), + ), + ); it('renders correctly', () => { const fixture = MockRender(TargetComponent); expect(fixture.nativeElement.innerHTML).toContain(`'pipe:'`); - expect(fixture.nativeElement.innerHTML).toContain(`'s:transform:'`); + expect(fixture.nativeElement.innerHTML).toContain( + `'s:transform:'`, + ); expect(fixture.nativeElement.innerHTML).toContain(`'s:name:'`); expect(fixture.nativeElement.innerHTML).toContain(`'s:echo:'`); }); }); describe('guts:mock-instance', () => { - beforeEach(() => TestBed.configureTestingModule(ngMocks.guts(TargetComponent, TargetModule))); + beforeEach(() => + TestBed.configureTestingModule( + ngMocks.guts(TargetComponent, TargetModule), + ), + ); beforeAll(() => MockInstance(TargetPipe, instance => @@ -81,10 +115,18 @@ describe('pipe-as-service', () => { it('renders correctly', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain(`'pipe:transform'`); - expect(fixture.nativeElement.innerHTML).toContain(`'s:transform:transform'`); - expect(fixture.nativeElement.innerHTML).toContain(`'s:name:mock'`); - expect(fixture.nativeElement.innerHTML).toContain(`'s:echo:echo'`); + expect(fixture.nativeElement.innerHTML).toContain( + `'pipe:transform'`, + ); + expect(fixture.nativeElement.innerHTML).toContain( + `'s:transform:transform'`, + ); + expect(fixture.nativeElement.innerHTML).toContain( + `'s:name:mock'`, + ); + expect(fixture.nativeElement.innerHTML).toContain( + `'s:echo:echo'`, + ); }); }); @@ -95,7 +137,9 @@ describe('pipe-as-service', () => { const fixture = MockRender(TargetComponent); expect(fixture.nativeElement.innerHTML).toContain(`'pipe:'`); - expect(fixture.nativeElement.innerHTML).toContain(`'s:transform:'`); + expect(fixture.nativeElement.innerHTML).toContain( + `'s:transform:'`, + ); expect(fixture.nativeElement.innerHTML).toContain(`'s:name:'`); expect(fixture.nativeElement.innerHTML).toContain(`'s:echo:'`); }); @@ -118,21 +162,38 @@ describe('pipe-as-service', () => { it('renders correctly', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain(`'pipe:transform'`); - expect(fixture.nativeElement.innerHTML).toContain(`'s:transform:transform'`); - expect(fixture.nativeElement.innerHTML).toContain(`'s:name:mock'`); - expect(fixture.nativeElement.innerHTML).toContain(`'s:echo:echo'`); + expect(fixture.nativeElement.innerHTML).toContain( + `'pipe:transform'`, + ); + expect(fixture.nativeElement.innerHTML).toContain( + `'s:transform:transform'`, + ); + expect(fixture.nativeElement.innerHTML).toContain( + `'s:name:mock'`, + ); + expect(fixture.nativeElement.innerHTML).toContain( + `'s:echo:echo'`, + ); }); }); describe('mock-builder:pipe-function', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).mock(TargetPipe, () => 'transform')); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule).mock( + TargetPipe, + () => 'transform', + ), + ); it('renders correctly', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain(`'pipe:transform'`); - expect(fixture.nativeElement.innerHTML).toContain(`'s:transform:transform'`); + expect(fixture.nativeElement.innerHTML).toContain( + `'pipe:transform'`, + ); + expect(fixture.nativeElement.innerHTML).toContain( + `'s:transform:transform'`, + ); expect(fixture.nativeElement.innerHTML).toContain(`'s:name:'`); expect(fixture.nativeElement.innerHTML).toContain(`'s:echo:'`); }); @@ -147,7 +208,9 @@ describe('pipe-as-service', () => { ); it('fails because of the missed function', () => { - expect(() => MockRender(TargetComponent)).toThrowError(/.echo is not a function/); + expect(() => MockRender(TargetComponent)).toThrowError( + /.echo is not a function/, + ); }); }); @@ -163,10 +226,18 @@ describe('pipe-as-service', () => { it('renders correctly', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain(`'pipe:transform'`); - expect(fixture.nativeElement.innerHTML).toContain(`'s:transform:transform'`); - expect(fixture.nativeElement.innerHTML).toContain(`'s:name:test'`); - expect(fixture.nativeElement.innerHTML).toContain(`'s:echo:echo'`); + expect(fixture.nativeElement.innerHTML).toContain( + `'pipe:transform'`, + ); + expect(fixture.nativeElement.innerHTML).toContain( + `'s:transform:transform'`, + ); + expect(fixture.nativeElement.innerHTML).toContain( + `'s:name:test'`, + ); + expect(fixture.nativeElement.innerHTML).toContain( + `'s:echo:echo'`, + ); }); }); }); diff --git a/tests/provider-with-custom-dependencies/test.spec.ts b/tests/provider-with-custom-dependencies/test.spec.ts index 403a6b9e62..aea33ecfc2 100644 --- a/tests/provider-with-custom-dependencies/test.spec.ts +++ b/tests/provider-with-custom-dependencies/test.spec.ts @@ -1,4 +1,12 @@ -import { Component, Injectable as InjectableSource, NgModule, Optional, Self, SkipSelf, VERSION } from '@angular/core'; +import { + Component, + Injectable as InjectableSource, + NgModule, + Optional, + Self, + SkipSelf, + VERSION, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { MockBuilder, MockRender } from 'ng-mocks'; @@ -40,7 +48,8 @@ class TargetService { @Component({ selector: 'target', template: ` - "service:{{ service.service ? service.service.name : 'missed' }}" "optional:{{ + "service:{{ service.service ? service.service.name : 'missed' }}" + "optional:{{ service.optional ? service.optional.name : 'missed' }}" `, @@ -58,7 +67,11 @@ class TargetComponent { useValue: undefined, }, { - deps: [Dep2Service, [new Optional(), new SkipSelf(), new Self(), Dep3Service], 'test'], + deps: [ + Dep2Service, + [new Optional(), new SkipSelf(), new Self(), Dep3Service], + 'test', + ], provide: TargetService, useClass: TargetService, }, @@ -84,43 +97,63 @@ describe('provider-with-custom-dependencies', () => { const fixture = TestBed.createComponent(TargetComponent); fixture.detectChanges(); // Injects root dependency correctly. - expect(fixture.nativeElement.innerHTML).toContain('"service:dep-2"'); + expect(fixture.nativeElement.innerHTML).toContain( + '"service:dep-2"', + ); // Skips unprovided local dependency. - expect(fixture.nativeElement.innerHTML).toContain('"optional:missed"'); + expect(fixture.nativeElement.innerHTML).toContain( + '"optional:missed"', + ); // The dependency should not be provided in TestBed. - expect(() => TestBed.get(Dep3Service)).toThrowError(/No provider for Dep3Service/); + expect(() => TestBed.get(Dep3Service)).toThrowError( + /No provider for Dep3Service/, + ); }); }); describe('mock-builder:mock', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(TargetService)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule).keep(TargetService), + ); it('creates component with mock custom dependencies', () => { const fixture = MockRender(TargetComponent); // Injects root dependency correctly, it is not missed, it is replaced with a mock copy. expect(fixture.nativeElement.innerHTML).toContain('"service:"'); // Skips unprovided local dependency despite its mock copy. - expect(fixture.nativeElement.innerHTML).toContain('"optional:missed"'); + expect(fixture.nativeElement.innerHTML).toContain( + '"optional:missed"', + ); // The dependency should not be provided in TestBed. - expect(() => TestBed.get(Dep3Service)).toThrowError(/No provider for Dep3Service/); + expect(() => TestBed.get(Dep3Service)).toThrowError( + /No provider for Dep3Service/, + ); }); }); describe('mock-builder:keep', () => { beforeEach(() => - MockBuilder(TargetComponent, TargetModule).keep(TargetService).keep(Dep2Service, { - dependency: true, - }), + MockBuilder(TargetComponent, TargetModule) + .keep(TargetService) + .keep(Dep2Service, { + dependency: true, + }), ); it('creates component with kept Dep2Service', () => { const fixture = MockRender(TargetComponent); // Injects root dependency correctly, it is not missed, it is replaced with a mock copy. - expect(fixture.nativeElement.innerHTML).toContain('"service:dep-2"'); + expect(fixture.nativeElement.innerHTML).toContain( + '"service:dep-2"', + ); // Skips unprovided local dependency despite its mock copy. - expect(fixture.nativeElement.innerHTML).toContain('"optional:missed"'); + expect(fixture.nativeElement.innerHTML).toContain( + '"optional:missed"', + ); // The dependency should not be provided in TestBed. - expect(() => TestBed.get(Dep3Service)).toThrowError(/No provider for Dep3Service/); + expect(() => TestBed.get(Dep3Service)).toThrowError( + /No provider for Dep3Service/, + ); }); }); }); diff --git a/tests/provider-with-dependency/test.spec.ts b/tests/provider-with-dependency/test.spec.ts index 7e7ccc99ad..6aed68362d 100644 --- a/tests/provider-with-dependency/test.spec.ts +++ b/tests/provider-with-dependency/test.spec.ts @@ -26,7 +26,9 @@ describe('provider-with-dependency:real', () => { it('should render "parent"', () => { const fixture = MockRender(InternalComponent); - expect(fixture.debugElement.nativeElement.innerHTML).toEqual('replaced'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'replaced', + ); }); }); @@ -47,7 +49,9 @@ describe('provider-with-dependency:provided', () => { it('should render "parent"', () => { const fixture = MockRender(InternalComponent); - expect(fixture.debugElement.nativeElement.innerHTML).toEqual('mock'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'mock', + ); }); }); @@ -67,6 +71,8 @@ describe('provider-with-dependency:mock', () => { it('should render "parent" even the providers where patched', () => { const fixture = MockRender(InternalComponent); - expect(fixture.debugElement.nativeElement.innerHTML).toEqual('mock'); + expect(fixture.nativeElement.innerHTML).toEqual( + 'mock', + ); }); }); diff --git a/tests/rerender-rendered-content-child/test.spec.ts b/tests/rerender-rendered-content-child/test.spec.ts index ed2756eb70..0b857fc352 100644 --- a/tests/rerender-rendered-content-child/test.spec.ts +++ b/tests/rerender-rendered-content-child/test.spec.ts @@ -1,4 +1,9 @@ -import { MockBuilder, MockComponent, MockRender, ngMocks } from 'ng-mocks'; +import { + MockBuilder, + MockComponent, + MockRender, + ngMocks, +} from 'ng-mocks'; import { ContentChildComponent } from './fixtures.components'; @@ -23,20 +28,23 @@ describe('Rerender of a rendered @ContentChild', () => { }, ); expect(fixture).toBeDefined(); - expect(fixture.debugElement.nativeElement.innerHTML).toContain('$implicit 1'); + expect(fixture.nativeElement.innerHTML).toContain('$implicit 1'); fixture.componentInstance.outside = '2'; fixture.detectChanges(); - expect(fixture.debugElement.nativeElement.innerHTML).toContain('$implicit 2'); + expect(fixture.nativeElement.innerHTML).toContain('$implicit 2'); - const component = ngMocks.find(fixture.debugElement, MockComponent(ContentChildComponent)).componentInstance; + const component = ngMocks.find( + fixture.debugElement, + MockComponent(ContentChildComponent), + ).componentInstance; component.__render('block', 'updated'); fixture.detectChanges(); - expect(fixture.debugElement.nativeElement.innerHTML).toContain('updated 2'); + expect(fixture.nativeElement.innerHTML).toContain('updated 2'); fixture.componentInstance.outside = '3'; fixture.detectChanges(); - expect(fixture.debugElement.nativeElement.innerHTML).toContain('updated 3'); + expect(fixture.nativeElement.innerHTML).toContain('updated 3'); }); }); diff --git a/tests/root-provider-in-depths/test.spec.ts b/tests/root-provider-in-depths/test.spec.ts index 35f9daa97b..ce30199fdb 100644 --- a/tests/root-provider-in-depths/test.spec.ts +++ b/tests/root-provider-in-depths/test.spec.ts @@ -38,7 +38,13 @@ class TargetComponent { @NgModule({ declarations: [TargetComponent], exports: [TargetComponent], - providers: [Nested1Service, [Nested2Service, [Nested3Service, [Nested4Service, [TargetService]]]]], + providers: [ + Nested1Service, + [ + Nested2Service, + [Nested3Service, [Nested4Service, [TargetService]]], + ], + ], }) class TargetModule {} @@ -58,7 +64,9 @@ describe('root-provider-in-depths', () => { }); describe('mock-builder', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(TargetService)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule).keep(TargetService), + ); it('creates component with very nested service', () => { const fixture = MockRender(TargetComponent); diff --git a/tests/root-provider-with-root-dep/test.spec.ts b/tests/root-provider-with-root-dep/test.spec.ts index 2fb08722da..d6667801ec 100644 --- a/tests/root-provider-with-root-dep/test.spec.ts +++ b/tests/root-provider-with-root-dep/test.spec.ts @@ -1,4 +1,11 @@ -import { Component, Inject, Injectable as InjectableSource, InjectionToken, NgModule, VERSION } from '@angular/core'; +import { + Component, + Inject, + Injectable as InjectableSource, + InjectionToken, + NgModule, + VERSION, +} from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { MockBuilder, MockRender } from 'ng-mocks'; @@ -55,7 +62,9 @@ describe('root-provider-with-root-dep', () => { it('finds tokens', () => { const fixture = TestBed.createComponent(TargetComponent); fixture.detectChanges(); - expect(fixture.nativeElement.innerHTML).toContain('"name:token"'); + expect(fixture.nativeElement.innerHTML).toContain( + '"name:token"', + ); }); }); diff --git a/tests/root-provider-with-string-dep/test.spec.ts b/tests/root-provider-with-string-dep/test.spec.ts index 0548b3f66b..63e3697f83 100644 --- a/tests/root-provider-with-string-dep/test.spec.ts +++ b/tests/root-provider-with-string-dep/test.spec.ts @@ -31,7 +31,9 @@ describe('root-provider-with-string-dep', () => { ); it('finds tokens', () => { - expect(() => TestBed.createComponent(TargetComponent)).toThrowError(/No provider for name!/); + expect(() => + TestBed.createComponent(TargetComponent), + ).toThrowError(/No provider for name!/); }); }); @@ -39,7 +41,9 @@ describe('root-provider-with-string-dep', () => { beforeEach(() => MockBuilder(TargetComponent, TargetModule)); it('mocks service', () => { - expect(() => MockRender(TargetComponent)).toThrowError(/No provider for name!/); + expect(() => MockRender(TargetComponent)).toThrowError( + /No provider for name!/, + ); }); }); }); diff --git a/tests/root-providers/fixtures.ts b/tests/root-providers/fixtures.ts new file mode 100644 index 0000000000..3382e0a6c9 --- /dev/null +++ b/tests/root-providers/fixtures.ts @@ -0,0 +1,93 @@ +import { + Component, + Inject, + Injectable as InjectableSource, + InjectionToken, + Injector, + NgModule, + Optional, + SkipSelf, +} from '@angular/core'; +import { BrowserModule } from '@angular/platform-browser'; +import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; + +// Because of A5 we need to cast Injectable to any type. +// But because of A10+ we need to do it via a middle function. +function Injectable(...args: any[]): any { + return InjectableSource(...args); +} + +// Thanks A5. +export const TOKEN = new (InjectionToken as any)('TOKEN', { + factory: () => 'token', +}); + +@Injectable() +export class ModuleService { + public readonly name = 'module'; +} + +@Injectable({ + providedIn: 'root', +}) +export class TargetService { + public readonly name = 'service'; +} + +@Injectable({ + providedIn: 'root', +}) +export class FakeService { + public readonly name = 'fake'; +} + +@Injectable({ + providedIn: 'any', +}) +export class ProvidedService { + public readonly name = 'provided'; +} + +@Component({ + selector: 'target', + template: ` + "service:{{ service.name }}" "fake:{{ fake.name }}" "injected:{{ injected.name }}" "provided:{{ provided.name }}" + "token:{{ token }}" + `, +}) +export class TargetComponent { + public readonly injected: TargetService; + + public constructor( + @Inject(FakeService) public readonly fake: TargetService, + @Optional() + @Inject(TOKEN) + @SkipSelf() + public readonly token: string, + @Optional() @SkipSelf() public readonly service: TargetService, + @Inject(TOKEN) + @Optional() + @SkipSelf() + public readonly token2: string, + public readonly provided: ProvidedService, + injector: Injector, + ) { + this.injected = injector.get(TargetService); + } +} + +@Component({ + selector: 'module', + template: `{{ module.name }}`, +}) +export class ModuleComponent { + public constructor(public readonly module: ModuleService) {} +} + +@NgModule({ + declarations: [TargetComponent, ModuleComponent], + exports: [TargetComponent], + imports: [BrowserModule, BrowserAnimationsModule], + providers: [ProvidedService], +}) +export class TargetModule {} diff --git a/tests/root-providers/test.spec.ts b/tests/root-providers/test.spec.ts index 53ea50334d..f988d9d9c2 100644 --- a/tests/root-providers/test.spec.ts +++ b/tests/root-providers/test.spec.ts @@ -1,93 +1,19 @@ -import { - Component, - Inject, - Injectable as InjectableSource, - InjectionToken, - Injector, - NgModule, - Optional, - SkipSelf, - VERSION, -} from '@angular/core'; +import { VERSION } from '@angular/core'; import { TestBed } from '@angular/core/testing'; -import { BrowserModule } from '@angular/platform-browser'; -import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; -import { MockBuilder, MockRender, ngMocks, NG_MOCKS_ROOT_PROVIDERS } from 'ng-mocks'; - -// Because of A5 we need to cast Injectable to any type. -// But because of A10+ we need to do it via a middle function. -function Injectable(...args: any[]): any { - return InjectableSource(...args); -} - -// Thanks A5. -const TOKEN = new (InjectionToken as any)('TOKEN', { - factory: () => 'token', -}); +import { + MockBuilder, + MockRender, + ngMocks, + NG_MOCKS_ROOT_PROVIDERS, +} from 'ng-mocks'; -@Injectable() -class ModuleService { - public readonly name = 'module'; -} - -@Injectable({ - providedIn: 'root', -}) -class TargetService { - public readonly name = 'service'; -} - -@Injectable({ - providedIn: 'root', -}) -class FakeService { - public readonly name = 'fake'; -} - -@Injectable({ - providedIn: 'any', -}) -class ProvidedService { - public readonly name = 'provided'; -} - -@Component({ - selector: 'target', - template: ` - "service:{{ service.name }}" "fake:{{ fake.name }}" "injected:{{ injected.name }}" "provided:{{ provided.name }}" - "token:{{ token }}" - `, -}) -class TargetComponent { - public readonly injected: TargetService; - - public constructor( - @Inject(FakeService) public readonly fake: TargetService, - @Optional() @Inject(TOKEN) @SkipSelf() public readonly token: string, - @Optional() @SkipSelf() public readonly service: TargetService, - @Inject(TOKEN) @Optional() @SkipSelf() public readonly token2: string, - public readonly provided: ProvidedService, - injector: Injector, - ) { - this.injected = injector.get(TargetService); - } -} - -@Component({ - selector: 'module', - template: `{{ module.name }}`, -}) -class ModuleComponent { - public constructor(public readonly module: ModuleService) {} -} - -@NgModule({ - declarations: [TargetComponent, ModuleComponent], - exports: [TargetComponent], - imports: [BrowserModule, BrowserAnimationsModule], - providers: [ProvidedService], -}) -class TargetModule {} +import { + ModuleComponent, + TargetComponent, + TargetModule, + TargetService, + TOKEN, +} from './fixtures'; describe('root-providers', () => { beforeEach(() => { @@ -106,34 +32,56 @@ describe('root-providers', () => { it('finds tokens', () => { const fixture = TestBed.createComponent(TargetComponent); fixture.detectChanges(); - expect(fixture.nativeElement.innerHTML).toContain('"service:service"'); - expect(fixture.nativeElement.innerHTML).toContain('"fake:fake"'); - expect(fixture.nativeElement.innerHTML).toContain('"injected:service"'); - expect(fixture.nativeElement.innerHTML).toContain('"provided:provided"'); - expect(fixture.nativeElement.innerHTML).toContain('"token:token"'); + expect(fixture.nativeElement.innerHTML).toContain( + '"service:service"', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '"fake:fake"', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '"injected:service"', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '"provided:provided"', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '"token:token"', + ); }); it('fails', () => { - expect(() => TestBed.createComponent(ModuleComponent)).toThrowError(/-> ModuleService/); + expect(() => + TestBed.createComponent(ModuleComponent), + ).toThrowError(/-> ModuleService/); }); }); describe('mock', () => { ngMocks.faster(); - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(ModuleComponent)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule).keep( + ModuleComponent, + ), + ); it('uses mock providers', () => { const fixture = MockRender(TargetComponent); expect(fixture.nativeElement.innerHTML).toContain('"service:"'); expect(fixture.nativeElement.innerHTML).toContain('"fake:"'); - expect(fixture.nativeElement.innerHTML).toContain('"injected:"'); - expect(fixture.nativeElement.innerHTML).toContain('"provided:"'); + expect(fixture.nativeElement.innerHTML).toContain( + '"injected:"', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '"provided:"', + ); expect(fixture.nativeElement.innerHTML).toContain('"token:"'); }); it('fails', () => { - expect(() => MockRender(ModuleComponent)).toThrowError(/-> ModuleService/); + expect(() => MockRender(ModuleComponent)).toThrowError( + /-> ModuleService/, + ); }); }); @@ -141,57 +89,92 @@ describe('root-providers', () => { ngMocks.faster(); beforeEach(() => - MockBuilder(TargetComponent, TargetModule).mock(TargetService, TargetService, { - dependency: true, - }), + MockBuilder(TargetComponent, TargetModule).mock( + TargetService, + TargetService, + { + dependency: true, + }, + ), ); it('uses mock providers', () => { const fixture = MockRender(TargetComponent); expect(fixture.nativeElement.innerHTML).toContain('"service:"'); expect(fixture.nativeElement.innerHTML).toContain('"fake:"'); - expect(fixture.nativeElement.innerHTML).toContain('"injected:"'); - expect(fixture.nativeElement.innerHTML).toContain('"provided:"'); + expect(fixture.nativeElement.innerHTML).toContain( + '"injected:"', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '"provided:"', + ); expect(fixture.nativeElement.innerHTML).toContain('"token:"'); }); }); describe('keep', () => { - beforeEach(() => MockBuilder(TargetComponent, TargetModule).keep(TargetService)); + beforeEach(() => + MockBuilder(TargetComponent, TargetModule).keep(TargetService), + ); it('uses mock providers', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain('"service:service"'); + expect(fixture.nativeElement.innerHTML).toContain( + '"service:service"', + ); expect(fixture.nativeElement.innerHTML).toContain('"fake:"'); - expect(fixture.nativeElement.innerHTML).toContain('"injected:service"'); - expect(fixture.nativeElement.innerHTML).toContain('"provided:"'); + expect(fixture.nativeElement.innerHTML).toContain( + '"injected:service"', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '"provided:"', + ); expect(fixture.nativeElement.innerHTML).toContain('"token:"'); }); }); describe('keep via component module, but mocks root providers', () => { - beforeEach(() => MockBuilder(TargetModule).mock(NG_MOCKS_ROOT_PROVIDERS)); + beforeEach(() => + MockBuilder(TargetModule).mock(NG_MOCKS_ROOT_PROVIDERS), + ); it('uses mock providers', () => { const fixture = MockRender(TargetComponent); expect(fixture.nativeElement.innerHTML).toContain('"service:"'); expect(fixture.nativeElement.innerHTML).toContain('"fake:"'); - expect(fixture.nativeElement.innerHTML).toContain('"injected:"'); - expect(fixture.nativeElement.innerHTML).toContain('"provided:provided"'); // It is in the module. + expect(fixture.nativeElement.innerHTML).toContain( + '"injected:"', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '"provided:provided"', + ); // It is in the module. expect(fixture.nativeElement.innerHTML).toContain('"token:"'); }); }); describe('keep via component module, and keeps root providers', () => { - beforeEach(() => MockBuilder(TargetModule).mock(NG_MOCKS_ROOT_PROVIDERS).keep(TargetService).keep(TOKEN)); + beforeEach(() => + MockBuilder(TargetModule) + .mock(NG_MOCKS_ROOT_PROVIDERS) + .keep(TargetService) + .keep(TOKEN), + ); it('uses mock providers', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain('"service:service"'); + expect(fixture.nativeElement.innerHTML).toContain( + '"service:service"', + ); expect(fixture.nativeElement.innerHTML).toContain('"fake:"'); - expect(fixture.nativeElement.innerHTML).toContain('"injected:service"'); - expect(fixture.nativeElement.innerHTML).toContain('"provided:provided"'); // It is in the module. - expect(fixture.nativeElement.innerHTML).toContain('"token:token"'); + expect(fixture.nativeElement.innerHTML).toContain( + '"injected:service"', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '"provided:provided"', + ); // It is in the module. + expect(fixture.nativeElement.innerHTML).toContain( + '"token:token"', + ); }); }); @@ -204,10 +187,16 @@ describe('root-providers', () => { it('uses mock providers', () => { const fixture = MockRender(TargetComponent); - expect(fixture.nativeElement.innerHTML).toContain('"service:service"'); + expect(fixture.nativeElement.innerHTML).toContain( + '"service:service"', + ); expect(fixture.nativeElement.innerHTML).toContain('"fake:"'); - expect(fixture.nativeElement.innerHTML).toContain('"injected:service"'); - expect(fixture.nativeElement.innerHTML).toContain('"provided:"'); + expect(fixture.nativeElement.innerHTML).toContain( + '"injected:service"', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '"provided:"', + ); expect(fixture.nativeElement.innerHTML).toContain('"token:"'); }); }); diff --git a/tests/shared-mocked-module/test.spec.ts b/tests/shared-mocked-module/test.spec.ts index c23faf4e73..561895d25e 100644 --- a/tests/shared-mocked-module/test.spec.ts +++ b/tests/shared-mocked-module/test.spec.ts @@ -1,4 +1,9 @@ -import { MockBuilder, MockComponent, MockRender, ngMocks } from 'ng-mocks'; +import { + MockBuilder, + MockComponent, + MockRender, + ngMocks, +} from 'ng-mocks'; import { MyComponent, TargetComponent } from './fixtures.components'; import { TargetModule } from './fixtures.modules'; @@ -9,7 +14,7 @@ describe('SharedMockModule:real', () => { it('should render', () => { const fixture = MockRender(TargetComponent); expect(fixture).toBeDefined(); - const content = fixture.debugElement.nativeElement.innerHTML; + const content = fixture.nativeElement.innerHTML; expect(content).toContain( 'child:1 real content', ); @@ -20,16 +25,25 @@ describe('SharedMockModule:real', () => { }); describe('SharedMockModule:mock', () => { - beforeEach(() => MockBuilder(TargetComponent).keep(TargetModule).mock(MyComponent)); + beforeEach(() => + MockBuilder(TargetComponent).keep(TargetModule).mock(MyComponent), + ); // The expectation is to verify that only MyComponent was replaced with a mock copy, even it was deeply nested. it('should render', () => { const fixture = MockRender(TargetComponent); expect(fixture).toBeDefined(); - const content = fixture.debugElement.nativeElement.innerHTML; - const component = ngMocks.find(fixture.debugElement, MockComponent(MyComponent)).componentInstance; + const content = fixture.nativeElement.innerHTML; + const component = ngMocks.find( + fixture.debugElement, + MockComponent(MyComponent), + ).componentInstance; expect(component).toBeDefined(); - expect(content).toContain('child:1 '); - expect(content).toContain('child:2 '); + expect(content).toContain( + 'child:1 ', + ); + expect(content).toContain( + 'child:2 ', + ); }); }); diff --git a/tests/spies/test.spec.ts b/tests/spies/test.spec.ts index 652103d43c..322f2a2e6b 100644 --- a/tests/spies/test.spec.ts +++ b/tests/spies/test.spec.ts @@ -2,7 +2,12 @@ import { Component, Injectable, NgModule } from '@angular/core'; import { inject } from '@angular/core/testing'; -import { MockBuilder, MockRender, MockService, ngMocks } from 'ng-mocks'; +import { + MockBuilder, + MockRender, + MockService, + ngMocks, +} from 'ng-mocks'; @Injectable() class TargetService { @@ -38,7 +43,10 @@ describe('spies:real', () => { it('should render', () => { const fixture = MockRender(TargetComponent); - const component = ngMocks.find(fixture.debugElement, TargetComponent).componentInstance; + const component = ngMocks.find( + fixture.debugElement, + TargetComponent, + ).componentInstance; expect(component).toBeDefined(); expect(component.echo()).toEqual('TargetComponent'); }); @@ -54,19 +62,28 @@ describe('spies:manual-mock', () => { } (spy as any).manual = true; - return MockBuilder(TargetComponent, TargetModule).mock(TargetService, spy); + return MockBuilder(TargetComponent, TargetModule).mock( + TargetService, + spy, + ); }); - it('should get manually mock service', inject([TargetService], (targetService: TargetService) => { - expect((targetService as any).manual).toBe(true); - const fixture = MockRender(TargetComponent); - const component = ngMocks.find(fixture.debugElement, TargetComponent).componentInstance; - expect(component).toBeDefined(); - expect(targetService.echo).toHaveBeenCalledTimes(1); - expect(targetService.echo).toHaveBeenCalledWith('constructor'); - expect(component.echo()).toEqual('fake'); - expect(targetService.echo).toHaveBeenCalledTimes(2); - })); + it('should get manually mock service', inject( + [TargetService], + (targetService: TargetService) => { + expect((targetService as any).manual).toBe(true); + const fixture = MockRender(TargetComponent); + const component = ngMocks.find( + fixture.debugElement, + TargetComponent, + ).componentInstance; + expect(component).toBeDefined(); + expect(targetService.echo).toHaveBeenCalledTimes(1); + expect(targetService.echo).toHaveBeenCalledWith('constructor'); + expect(component.echo()).toEqual('fake'); + expect(targetService.echo).toHaveBeenCalledTimes(2); + }, + )); }); describe('spies:auto-mock', () => { @@ -75,14 +92,21 @@ describe('spies:auto-mock', () => { it('should get an existing mock service', () => { const fixture = MockRender(TargetComponent); const targetService = fixture.point.injector.get(TargetService); - const component = ngMocks.find(fixture.debugElement, TargetComponent).componentInstance; + const component = ngMocks.find( + fixture.debugElement, + TargetComponent, + ).componentInstance; expect(component).toBeDefined(); expect(targetService.echo).toHaveBeenCalledTimes(1); expect(targetService.echo).toHaveBeenCalledWith('constructor'); if (typeof jest !== 'undefined') { - ngMocks.stub(targetService, 'echo').mockReturnValue('faked'); + ngMocks + .stub(targetService, 'echo') + .mockReturnValue('faked'); } else if (typeof jasmine !== 'undefined') { - ngMocks.stub(targetService, 'echo').and.returnValue('faked'); + ngMocks + .stub(targetService, 'echo') + .and.returnValue('faked'); } expect(component.echo()).toEqual('faked'); expect(targetService.echo).toHaveBeenCalledTimes(2); diff --git a/tests/structural-directives/structural-directives.spec.ts b/tests/structural-directives/structural-directives.spec.ts index c87d997c7a..354f16522b 100644 --- a/tests/structural-directives/structural-directives.spec.ts +++ b/tests/structural-directives/structural-directives.spec.ts @@ -1,6 +1,13 @@ // tslint:disable max-file-line-count -import { isMockOf, MockBuilder, MockDirective, MockedDirective, MockRender, ngMocks } from 'ng-mocks'; +import { + isMockOf, + MockBuilder, + MockDirective, + MockedDirective, + MockRender, + ngMocks, +} from 'ng-mocks'; import { CustomNgForWithOfDirective } from './custom-ng-for-with-of.directive'; import { CustomNgForWithoutOfDirective } from './custom-ng-for-without-of.directive'; @@ -8,7 +15,10 @@ import { CustomNgIfDirective } from './custom-ng-if.directive'; describe('structural-directive-as-ng-for:real', () => { beforeEach(() => - MockBuilder().keep(CustomNgForWithOfDirective).keep(CustomNgForWithoutOfDirective).keep(CustomNgIfDirective), + MockBuilder() + .keep(CustomNgForWithOfDirective) + .keep(CustomNgForWithoutOfDirective) + .keep(CustomNgIfDirective), ); it('renders customNgForWithOf properly', () => { @@ -25,9 +35,15 @@ describe('structural-directive-as-ng-for:real', () => { ); // every value should be rendered correctly. - expect(fixture.nativeElement.innerHTML).toContain('
    w/ string1010
    '); - expect(fixture.nativeElement.innerHTML).toContain('
    w/ string2100
    '); - expect(fixture.nativeElement.innerHTML).toContain('
    w/ string3201
    '); + expect(fixture.nativeElement.innerHTML).toContain( + '
    w/ string1010
    ', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '
    w/ string2100
    ', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '
    w/ string3201
    ', + ); }); it('renders customNgForWithoutOf properly', () => { @@ -44,9 +60,15 @@ describe('structural-directive-as-ng-for:real', () => { ); // every value should be rendered correctly. - expect(fixture.nativeElement.innerHTML).toContain('
    w/o string1010
    '); - expect(fixture.nativeElement.innerHTML).toContain('
    w/o string2100
    '); - expect(fixture.nativeElement.innerHTML).toContain('
    w/o string3201
    '); + expect(fixture.nativeElement.innerHTML).toContain( + '
    w/o string1010
    ', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '
    w/o string2100
    ', + ); + expect(fixture.nativeElement.innerHTML).toContain( + '
    w/o string3201
    ', + ); }); it('renders customNgIf properly', () => { @@ -62,14 +84,21 @@ describe('structural-directive-as-ng-for:real', () => { ); // only first div should be rendered. - expect(fixture.nativeElement.innerHTML).toContain('
    should be shown
    '); - expect(fixture.nativeElement.innerHTML).not.toContain('
    should be hidden
    '); + expect(fixture.nativeElement.innerHTML).toContain( + '
    should be shown
    ', + ); + expect(fixture.nativeElement.innerHTML).not.toContain( + '
    should be hidden
    ', + ); }); }); describe('structural-directive-as-ng-for:mock', () => { beforeEach(() => - MockBuilder().mock(CustomNgIfDirective).mock(CustomNgForWithOfDirective).mock(CustomNgForWithoutOfDirective), + MockBuilder() + .mock(CustomNgIfDirective) + .mock(CustomNgForWithOfDirective) + .mock(CustomNgForWithoutOfDirective), ); it('mocks customNgIf properly', () => { @@ -86,7 +115,10 @@ describe('structural-directive-as-ng-for:mock', () => { ); // we need to render mock structural directives manually - for (const instance of ngMocks.findInstances(fixture.debugElement, CustomNgIfDirective)) { + for (const instance of ngMocks.findInstances( + fixture.debugElement, + CustomNgIfDirective, + )) { if (isMockOf(instance, CustomNgIfDirective, 'd')) { instance.__render(undefined, { fromDirective: undefined, @@ -96,32 +128,45 @@ describe('structural-directive-as-ng-for:mock', () => { fixture.detectChanges(); // By default mock structural directives are rendered with undefined variables. - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).toContain(' $implicit: fromDirective: '); + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toContain(' $implicit: fromDirective: '); // Extracting mock. const debugElement = ngMocks.find(fixture.debugElement, 'div'); - const directive = ngMocks.get(debugElement, MockDirective(CustomNgIfDirective)); + const directive = ngMocks.get( + debugElement, + MockDirective(CustomNgIfDirective), + ); expect(directive).toBeTruthy(); if (!directive) { return; } // Assert that mock got right variables. - expect(directive.setValue).toEqual(['string1', 'string2', 'string3']); + expect(directive.setValue).toEqual([ + 'string1', + 'string2', + 'string3', + ]); // Now we want to assert how our html is rendered based on structural directive variables' definition. directive.__render(true, { fromDirective: false, }); fixture.detectChanges(); - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).toContain(' $implicit:true fromDirective:false '); + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toContain(' $implicit:true fromDirective:false '); // And we want dynamically change variables for render. directive.__render(false, { fromDirective: true, }); fixture.detectChanges(); - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).toContain(' $implicit:false fromDirective:true '); + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toContain(' $implicit:false fromDirective:true '); }); it('mocks CustomNgForWithOfDirective properly', () => { @@ -139,7 +184,10 @@ describe('structural-directive-as-ng-for:mock', () => { ); // we need to render mock structural directives manually - for (const instance of ngMocks.findInstances(fixture.debugElement, CustomNgForWithOfDirective)) { + for (const instance of ngMocks.findInstances( + fixture.debugElement, + CustomNgForWithOfDirective, + )) { if (isMockOf(instance, CustomNgForWithOfDirective, 'd')) { instance.__render(); } @@ -147,19 +195,28 @@ describe('structural-directive-as-ng-for:mock', () => { fixture.detectChanges(); // By default mock structural directives are rendered with undefined variables. - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).toContain(' w/ 00 '); + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toContain(' w/ 00 '); const debugElement = ngMocks.find(fixture.debugElement, 'div'); // Extracting mock. - const directive = ngMocks.get(debugElement, MockDirective(CustomNgForWithOfDirective)); + const directive = ngMocks.get( + debugElement, + MockDirective(CustomNgForWithOfDirective), + ); expect(directive).toBeTruthy(); if (!directive) { return; } // Assert that mock got right variables. - expect(directive.setItems).toEqual(['string1', 'string2', 'string3']); + expect(directive.setItems).toEqual([ + 'string1', + 'string2', + 'string3', + ]); // Now we want to assert how our html is rendered based on structural directive variables' definition. directive.__render('MainValue', { @@ -168,7 +225,9 @@ describe('structural-directive-as-ng-for:mock', () => { myLast: false, }); fixture.detectChanges(); - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).toContain(' w/ MainValueMyIndex10 '); + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toContain(' w/ MainValueMyIndex10 '); // And we want dynamically change variables for render. directive.__render('MainValue2', { @@ -177,7 +236,9 @@ describe('structural-directive-as-ng-for:mock', () => { myLast: true, }); fixture.detectChanges(); - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).toContain(' w/ MainValue2MyIndex201 '); + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toContain(' w/ MainValue2MyIndex201 '); }); it('mocks customNgForWithoutOf properly', () => { @@ -195,7 +256,10 @@ describe('structural-directive-as-ng-for:mock', () => { ); // we need to render mock structural directives manually - for (const instance of ngMocks.findInstances(fixture.debugElement, CustomNgForWithoutOfDirective)) { + for (const instance of ngMocks.findInstances( + fixture.debugElement, + CustomNgForWithoutOfDirective, + )) { if (isMockOf(instance, CustomNgForWithoutOfDirective, 'd')) { instance.__render(); } @@ -203,19 +267,28 @@ describe('structural-directive-as-ng-for:mock', () => { fixture.detectChanges(); // By default mock structural directives are rendered with undefined variables. - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).toContain(' w/o 00 '); + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toContain(' w/o 00 '); const debugElement = ngMocks.find(fixture.debugElement, 'div'); // Extracting mock. - const directive = ngMocks.get(debugElement, MockDirective(CustomNgForWithoutOfDirective)); + const directive = ngMocks.get( + debugElement, + MockDirective(CustomNgForWithoutOfDirective), + ); expect(directive).toBeTruthy(); if (!directive) { return; } // Assert that mock got right variables. - expect(directive.setItems).toEqual(['string1', 'string2', 'string3']); + expect(directive.setItems).toEqual([ + 'string1', + 'string2', + 'string3', + ]); // Now we want to assert how our html is rendered based on structural directive variables' definition. directive.__render('MainValue', { @@ -224,7 +297,9 @@ describe('structural-directive-as-ng-for:mock', () => { myLast: false, }); fixture.detectChanges(); - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).toContain(' w/o MainValueMyIndex10 '); + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toContain(' w/o MainValueMyIndex10 '); // And we want dynamically change variables for render. directive.__render('MainValue2', { @@ -233,11 +308,15 @@ describe('structural-directive-as-ng-for:mock', () => { myLast: true, }); fixture.detectChanges(); - expect(fixture.nativeElement.innerHTML.replace(/\s+/gm, ' ')).toContain(' w/o MainValue2MyIndex201 '); + expect( + fixture.nativeElement.innerHTML.replace(/\s+/gm, ' '), + ).toContain(' w/o MainValue2MyIndex201 '); }); it('searches for related directive', () => { - let mockDirective: MockedDirective | undefined; + let mockDirective: + | MockedDirective + | undefined; const fixture = MockRender( ` @@ -259,12 +338,18 @@ describe('structural-directive-as-ng-for:mock', () => { ); // we need to render mock structural directives manually - for (const instance of ngMocks.findInstances(fixture.debugElement, CustomNgForWithOfDirective)) { + for (const instance of ngMocks.findInstances( + fixture.debugElement, + CustomNgForWithOfDirective, + )) { if (isMockOf(instance, CustomNgForWithOfDirective, 'd')) { instance.__render(); } } - for (const instance of ngMocks.findInstances(fixture.debugElement, CustomNgForWithoutOfDirective)) { + for (const instance of ngMocks.findInstances( + fixture.debugElement, + CustomNgForWithoutOfDirective, + )) { if (isMockOf(instance, CustomNgForWithoutOfDirective, 'd')) { instance.__render(); } @@ -276,13 +361,21 @@ describe('structural-directive-as-ng-for:mock', () => { ngMocks.find(fixture.debugElement, '[data-type="node-1"]'), MockDirective(CustomNgForWithoutOfDirective), ); - expect(mockDirective.setItems).toEqual(['string1', 'string2', 'string3']); + expect(mockDirective.setItems).toEqual([ + 'string1', + 'string2', + 'string3', + ]); // Looking for second directive. mockDirective = ngMocks.get( ngMocks.find(fixture.debugElement, '[data-type="node-2"]'), MockDirective(CustomNgForWithoutOfDirective), ); - expect(mockDirective.setItems).toEqual(['string4', 'string5', 'string6']); + expect(mockDirective.setItems).toEqual([ + 'string4', + 'string5', + 'string6', + ]); }); }); diff --git a/tests/tokens-class/test.spec.ts b/tests/tokens-class/test.spec.ts index 96a692ace7..7699a73324 100644 --- a/tests/tokens-class/test.spec.ts +++ b/tests/tokens-class/test.spec.ts @@ -46,7 +46,9 @@ class TargetModule {} describe('tokens-class', () => { ngMocks.faster(); - beforeEach(() => MockBuilder().mock(TargetModule).keep(Class2Service)); + beforeEach(() => + MockBuilder().mock(TargetModule).keep(Class2Service), + ); it('resolves Class1Service as a mock instance', () => { const actual = TestBed.get(Class1Service); diff --git a/tests/tokens-existing/test.spec.ts b/tests/tokens-existing/test.spec.ts index 7b2ef0e380..f48025fd09 100644 --- a/tests/tokens-existing/test.spec.ts +++ b/tests/tokens-existing/test.spec.ts @@ -36,7 +36,9 @@ class TargetModule {} describe('tokens-existing', () => { ngMocks.faster(); - beforeEach(() => MockBuilder().mock(TargetModule).keep(Exist2Service)); + beforeEach(() => + MockBuilder().mock(TargetModule).keep(Exist2Service), + ); it('resolves TOKEN_EXISTING_MOCK as a mock service', () => { const actual = TestBed.get(TOKEN_EXISTING_MOCK); diff --git a/tslint.json b/tslint.json index f94fed5831..9f096f60cc 100644 --- a/tslint.json +++ b/tslint.json @@ -2,6 +2,7 @@ "extends": ["tslint:all", "tslint-jasmine-rules", "tslint-microsoft-contrib/recommended"], "rules": { "arrow-parens": false, + "arrow-return-shorthand": false, "comment-format": false, "completed-docs": false, "cyclomatic-complexity": [true, 10], From 2e8f5cf1cf57f202c726a07dcb45f3720e6a7644 Mon Sep 17 00:00:00 2001 From: MG Date: Sun, 29 Nov 2020 10:56:09 +0100 Subject: [PATCH 2/2] chore(release): v11.1.4 --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ba4434f96..bc3013e227 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [11.1.4](https://github.com/ike18t/ng-mocks/compare/v11.1.3...v11.1.4) (2020-11-29) + + +### Bug Fixes + +* a contemporary example ([d0e5efc](https://github.com/ike18t/ng-mocks/commit/d0e5efc435f40445718d6ce64604996073b37783)) + ## [11.1.3](https://github.com/ike18t/ng-mocks/compare/v11.1.2...v11.1.3) (2020-11-26)