异步测试确实贯穿所有功能

时间:2017-10-31 11:49:20

标签: angular unit-testing typescript karma-jasmine testbed

当我尝试在业力茉莉花中进行测试时,它应该通过2项服务。 然而,它一直到最后一个函数,但它没有返回其返回值。 有没有人知道它不会返回什么东西?

我以前的每次

 function checklistDbFactory(): PouchDB {
    // ... is just for sharing
    let db = new PouchDB("...");
    PouchDB.plugin(PouchFind);
    return db;
  }


  beforeEach(async(() => {

    TestBed.configureTestingModule({
      imports: [HttpModule],
      providers: [
        {provide: CHECKLIST_DB, useFactory: checklistDbFactory, deps: []},
        DatabaseService,
        IndexService,
        MockBackend,
        BaseRequestOptions,
        {
          provide: Http,
          useFactory: (backend, options) => new Http(backend, options),
          deps: [MockBackend, BaseRequestOptions]
        }
      ]
    });
    backend = TestBed.get(MockBackend);

    service = TestBed.get(IndexService);
  }));

我的测试本身

it('function should return expectd json', async(() => {
    backend.connections.subscribe(connection => {
      connection.mockRespond(new Response(<ResponseOptions>{
        body: JSON.stringify(expectJson)
      }));
    }); 
    console.log("getting into main thread");
    // ... is just for sharing
    service.filldatabase(inputJson, "...").then((data) => {
      console.log('getting into filldatabase');
      console.log(data);
    });
  }));

filldatabase函数

filldatabase(jsonfile, key) {
    console.log('Getting into filldatabase of 1service');
      return this.databaseService.fillPouch(JSON.parse(jsonfile['_body']), key).then( (data) => {
        console.log(data);
        console.log("Getting into then of fillPouch in 1st service");
        return true;
      }).catch( () => {
        console.log("getting into catch of fillpouch in 1service");
        return false;
      });
  }

fillPouch功能

fillPouch(json, key) {
    json._id = key;
    let push = this.db.put(
      json
    );
    console.log("push");
    console.log(push);

    return push;
  }

IntlliJ上的测试输出

'getting into main thread'
'Getting into filldatabase of 1service'
'push'
ZoneAwarePromise{__zone_symbol__state: null, __zone_symbol__value: []}

cmd上的测试输出

    ✔ Service should be created
LOG: 'getting into main thread'

LOG: 'getting into main thread'
LOG: 'getting into main thread'
LOG: 'getting into main thread'
LOG: 'Getting into filldatabase of 1service'
LOG: 'Getting into filldatabase of 1service'
LOG: 'Getting into filldatabase of 1service'
LOG: 'Getting into filldatabase of 1service'
LOG: 'push'
LOG: 'push'
LOG: 'push'
LOG: 'push'
LOG: ZoneAwarePromise{__zone_symbol__state: null, __zone_symbol__value: []}
LOG: ZoneAwarePromise{__zone_symbol__state: null, __zone_symbol__value: []}
LOG: ZoneAwarePromise{__zone_symbol__state: null, __zone_symbol__value: []}
LOG: ZoneAwarePromise{__zone_symbol__state: null, __zone_symbol__value: []}
.    ✔ function should return expectd json
// again file is just for sharing
31 10 2017 13:04:07.375:WARN [web-server]: 404: /assets/XML/<file>.json
LOG: 'Calling getJsonFromFile'

LOG: 'Calling getJsonFromFile'
LOG: 'Calling getJsonFromFile'
LOG: 'Calling getJsonFromFile'

这也是一些奇怪的东西。 Calling getJsonFromFilegetData() { this.databaseService.valueExist('checklistindex').then((data) => { if(!data) { console.log("Calling getJsonFromFile"); this.indexService.getJsonfromFile().subscribe((data) => { console.log(JSON.stringify(data)); this.indexService.filldatabase(data,'checklistindex' ); }) } }) } 。在我的app.component.ts里面。但我不会在任何地方打电话。

日志所在的函数是

application.config.php

你可以看到我在fillPouch里面一路走来。但它不会返回推送。或者其他任何事情。

2 个答案:

答案 0 :(得分:1)

Jasmine支持异步测试,你需要为它接受一个额外的参数:

it('function should return expectd json', async((done) => { // <-- add this parameter
    backend.connections.subscribe(connection => {
      connection.mockRespond(new Response(<ResponseOptions>{
        body: JSON.stringify(expectJson)
      }));
    }); 
    console.log("getting into main thread");
    // ... is just for sharing
    service.filldatabase(inputJson, "...").then((data) => {
      console.log('getting into filldatabase');
      console.log(data);
      done(); // <-- tell Jasmine you're finished
    });
  }));

传入的done函数会在你超时之前给你5秒(默认情况下),你可以用jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;改变它,如果你真的需要 - 虽然五秒很长时间已经过去了。

您可以对donebeforeEachit使用afterEach模式。

答案 1 :(得分:1)

通过以正确的方式模拟我的数据服务来解决这个问题。

<强> databaseServiceMock

import {DatabaseService} from "../../../../services/databaseService/databaseService";

export class DatabaseServiceMock extends DatabaseService {
  constructor() {
    super(null);
  }

  fillPouch(json, key) {
    return Promise.resolve(true);
  }

  valueExist(key) {
    return Promise.resolve(true);
  }

  getIndexVersion(key) {
    return Promise.resolve("TRIAL VERSION v2");
  }

  }

通过模拟databaseService,我必须在TestBed内进行一些调整。

我之前的每次

beforeEach(async(() => {

    TestBed.configureTestingModule({
      imports: [HttpModule],
      providers: [
        {provide:DatabaseService, useClass: DatabaseServiceMock},
        IndexService,
        MockBackend,
        BaseRequestOptions,
        {
          provide: Http,
          useFactory: (backend, options) => new Http(backend, options),
          deps: [MockBackend, BaseRequestOptions]
        }
      ]
    });
    backend = TestBed.get(MockBackend);

    service = TestBed.get(IndexService);
  }));

我的测试看起来像

it('function should return expectd json', async(() => {
    service.filldatabase(inputJson, "testpouch").then((data) => {
      expect(data).toBeTruthy();
    })
  }));

这个问题的问题在于this.db.put(json)因为我没有模拟我的数据库服务,所以它没有在这里进一步发展。我将fillPouch更改了一下,以便更容易测试。

我的fillPouch

fillPouch(json, key) {
json._id = key;
return this.db.put(json).then(() => {
  return Promise.resolve(true);
}).catch((error) => {
  return Promise.reject(false);
});

}

这一切都是通过PouchDB

完成的