Skip to content
master
Switch branches/tags
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

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');

About

Dependency injection lib for Egg.js.

Resources

Packages

No packages published