Dependency injection lib for Egg.js.
// 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();
}
}
// Foo
export default class Foo {
@inject(() => Bar) readonly bar: Bar;
}
// Bar
export default class Bar {
@inject(() => Foo) readonly foo: Foo;
}
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');