Skip to content

Commit

Permalink
Merge pull request #2096 from satanTime/issues/2087
Browse files Browse the repository at this point in the history
fix(MockInstance): correctly accepts falsy values #2087
  • Loading branch information
satanTime authored Mar 19, 2022
2 parents 3574bcb + 8900fc3 commit 1d8fc02
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 4 deletions.
8 changes: 4 additions & 4 deletions libs/ng-mocks/src/lib/mock-instance/mock-instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}

Expand Down Expand Up @@ -177,9 +177,9 @@ export function MockInstance<T>(
export function MockInstance<T>(declaration: Type<T> | AbstractType<T> | InjectionToken<T>, ...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);
}

Expand Down
60 changes: 60 additions & 0 deletions tests/issue-2087/test.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
});
}),
);
});

0 comments on commit 1d8fc02

Please sign in to comment.