Skip to content

Latest commit

 

History

History
114 lines (93 loc) · 2.42 KB

README.md

File metadata and controls

114 lines (93 loc) · 2.42 KB

egg-di

build status Test coverage NPM version npm download

Dependency injection lib for Egg.js.

use

// service
import { Context } from 'egg-di';
@Context
export class HackerNews extends Service {
  foo() { }
}

// other service
import { inject } from 'egg-di';
export class Foo extends Service {
  @inject()
  private readonly hackerNews: HackerNews;

  bar() {
    this.hackerNews.foo();
  }
}

// other controller
import { inject } from 'egg-di';
export class Foo extends Controller {
  @inject()
  private readonly hackerNews: HackerNews;

  bar() {
    this.hackerNews.foo();
  }
}

circular dependency

// Foo
export default class Foo {
  @inject(() => Bar) readonly bar: Bar;
}

// Bar
export default class Bar {
  @inject(() => Foo) readonly foo: Foo;
}

test

Test injected service.

// service
import { Context } from 'egg-di';
@Context
export class HackerNews extends Service {
  foo() { }
}

// hackernews.test.ts
import { getComponent } from 'egg-di';
describe('service/HackerNews.test.js', () => {
  const app = mm.app();
  let ctx: Context;
  let hackerNews: HackerNews;

  before(async () => {
    await app.ready();
    ctx = app.mockContext();
    hackerNews = getComponent(HackerNews, ctx);
  });

  it('getTopStories', async () => {
    const list = await hackerNews.getTopStories();
    assert(list.length === 30);
  });
});

Mock injected service.

// service
import { Context } from 'egg-di';
@Context
export class HackerNews extends Service {
  foo() { }
}

// bar.test.ts
import { getComponent } from 'egg-di';
const app = mm.app();
ctx = app.mockContext();
const hackerNews: HackerNews = getComponent(HackerNews, ctx);
mm.data(hackerNews, 'foo', 'hello');