【问题标题】:Async test does go trough all functions异步测试确实通过所有功能
【发布时间】:2018-04-12 13:54:56
【问题描述】:

当我尝试在 karma jasmine 中运行测试时,它应该通过 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(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 getJsonFromFile。在我的 app.component.ts 里面。但我不会在任何地方调用它。

日志所在的函数里面是

getData() {
    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' );
        })
      }
    })
  }

如你所见,我确实进入了我的填充袋。但是它不会返回推送。或任何类似的东西。

【问题讨论】:

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


    【解决方案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 函数会在超时前为您提供五秒(默认情况下),如果您确实需要,您可以使用jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; 更改此设置 - 尽管五秒已经很长了。

    您可以将done 模式用于beforeEachitafterEach

    【讨论】:

    • 我已经试过了,那是行不通的。但是我在我的问题中添加了一些可能有用的东西
    【解决方案2】:

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

    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),因为我没有模拟我的databaseService,它没有在这里更进一步。我稍微更改了 fillPouch 以使其更易于测试。

    我的填充袋

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

    }

    这一切都是用 PouchDB 完成的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 2020-10-08
      • 2019-11-01
      • 2018-01-25
      相关资源
      最近更新 更多