angular / in-memory-web-api

The code for this project has moved to the angular/angular repo. This repo is now archived.
MIT License
1.18k stars 231 forks source link

use case: use InMemoryDbService as a MockBackend in unit tests #116

Open asnowwolf opened 7 years ago

asnowwolf commented 7 years ago

We can use InMemoryDbService as a MockBackend in unit tests. It is very convenient in most simple scenes.

In this scenario we need:

  1. Make the resetDb method to public.
  2. All the data sources are cloned as working data, so as not to modify the original copy

Workground:

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpModule,
        InMemoryWebApiModule.forRoot(MockDbService),
      ],
      providers: [ProgramApi, InMemoryBackendService],
    });
  });

  let api: ProgramApi;
  let backend: InMemoryBackendService;

  beforeEach(inject([ProgramApi, InMemoryBackendService], (_api_: ProgramApi, _backend_: InMemoryBackendService) => {
    api = _api_;
    backend = _backend_;
  }));

  afterEach(() => {
    backend['resetDb']();
  });

  it('should create', () => {
    expect(api).toBeTruthy();
  });

  ...
winnemucca commented 7 years ago

I like this approach, but where are you getting ProgramApi (I realize this isn't part of angular)?

asnowwolf commented 7 years ago

It's a service of the application.