diff --git a/libs/ng-mocks/src/lib/mock-instance/mock-instance.ts b/libs/ng-mocks/src/lib/mock-instance/mock-instance.ts index b6aa066cef..480e79872d 100644 --- a/libs/ng-mocks/src/lib/mock-instance/mock-instance.ts +++ b/libs/ng-mocks/src/lib/mock-instance/mock-instance.ts @@ -42,8 +42,8 @@ const parseMockInstanceArgs = (args: any[]): MockInstanceArgs => { set.accessor = args[2]; } else { set.value = args[0]; - if (typeof set.value !== 'function') { - set.value = set.value?.init; + if (set.value && typeof set.value === 'object') { + set.value = set.value.init; } } @@ -177,9 +177,9 @@ export function MockInstance( export function MockInstance(declaration: Type | AbstractType | InjectionToken, ...args: any[]) { funcImportExists(declaration, 'MockInstance'); - const { key, value, accessor } = parseMockInstanceArgs(args); + if (args.length) { + const { key, value, accessor } = parseMockInstanceArgs(args); - if (value) { return mockInstanceConfig(declaration, key, value, accessor); } diff --git a/tests/issue-2087/test.spec.ts b/tests/issue-2087/test.spec.ts new file mode 100644 index 0000000000..b4d09bb872 --- /dev/null +++ b/tests/issue-2087/test.spec.ts @@ -0,0 +1,60 @@ +import { CommonModule } from '@angular/common'; +import { Component, Directive, NgModule } from '@angular/core'; +import { + MockBuilder, + MockInstance, + MockProvider, + MockRender, +} from 'ng-mocks'; + +@Directive({ + selector: 'target', +}) +class MockDirective { + public readonly boolean = false; + public readonly number = 0; + public readonly string = ''; +} + +@Component({ + selector: 'target', + template: ``, +}) +class TargetComponent { + public constructor(public readonly mock: MockDirective) {} +} + +@NgModule({ + declarations: [TargetComponent, MockDirective], + imports: [CommonModule], +}) +class TargetModule {} + +// MockInstance doesn't provide falsy values. +// @see https://github.com/ike18t/ng-mocks/issues/2087 +describe('issue-2087', () => { + MockInstance.scope(); + beforeEach(() => MockBuilder(TargetComponent, TargetModule)); + + const tests: Array<[keyof MockDirective, any, any]> = [ + ['string', '', 'test'], + ['number', 0, 1], + ['boolean', false, true], + ]; + + tests.forEach(([kind, falsy, truthy]) => + describe(kind, () => { + it(`works for falsy`, () => { + MockInstance(MockDirective, kind, falsy); + const fixture = MockRender(TargetComponent); + expect(fixture.componentInstance.mock[kind]).toEqual(falsy); + }); + + it(`works for truthy`, () => { + MockInstance(MockDirective, kind, truthy); + const fixture = MockRender(TargetComponent); + expect(fixture.componentInstance.mock[kind]).toEqual(truthy); + }); + }), + ); +});