Testing decorated constructor parameters

Viewed 561

I am trying to test a class which uses inversify for dependency injection and using @inject() to decorate parameters.

@injectable()
export class SaveManager {
    constructor(
        @inject(INJECTABLE.STORAGE) storage: IStorage, //Uncovered Line: 15
        @inject(Configuration) configuration: Configuration //Uncovered Line: 16
    ) {
        this.storage = storage;
        this.configuration = configuration;
    }
}

But the branch coverage of this class shows me that:

    @inject(INJECTABLE.STORAGE) storage: IStorage, //Uncovered Line: 15
    @inject(Configuration) configuration: Configuration //Uncovered Line: 16

These lines are not covered.

File                     |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line  
SaveManager.ts           |      100 |    66.67 |      100 |      100 |          15,16 

What should I test here to achieve 100% coverage and how can I test a constructor parameter decorator?

I know that I can use container.get() but I should be able to test decorators too.

1 Answers

With current versions of package dependencies code coverage works fine. You can use any of tests bellow and you will get 100% coverage of your SaveManager.

Resolve instance using InversifyJS:

test('Resolve SaveManager', () => {
    const manager = myContainer.get(SaveManager);
    expect(manager).not.toBe(null);
});

Create instance directly:

test('Create new SaveManager', () => {
    const storage = myContainer.get<IStorage>(INJECTABLE.STORAGE);
    const config = myContainer.get<Configuration>(Configuration);

    const manager = new SaveManager(storage, config);
    expect(manager).not.toBe(null);
});

Result coverage is in both cases:

 PASS  tests/save-manager.test.ts
---------------------|----------|----------|----------|----------|-------------------|
File                 |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------------|----------|----------|----------|----------|-------------------|
...
 save-manager.ts     |      100 |      100 |      100 |      100 |                   |
---------------------|----------|----------|----------|----------|-------------------|

Package versions used:

  • typescript 3.5.3
  • inversify 5.0.1
  • jest 24.9.0
  • reflect-metadata 0.1.13
Related