如何对依赖服务的组件方法进行单元测试?

时间:2019-11-01 10:42:47

标签: angular typescript jasmine karma-jasmine

我有以下方法,我需要在使用Jasmine和Karma时进行测试。据我所知,subscribe无法执行。在测试期间,变量addedToDBexistingInDB未更新,我的测试想断言它们是错误的。

addBank(name: string, country: string, pageurl: string, fromcurrency: string,
          tocurrencyxpath: string, buyxpath: string, sellxpath: string, unit: string) {
    this.service.postBank(name, country, pageurl, fromcurrency, tocurrencyxpath, buyxpath, sellxpath, unit).subscribe(
      data => {
        console.log('POST executed', data);
        if (name === '' || country === '' || pageurl === '' || fromcurrency === ''
          || tocurrencyxpath === '' || buyxpath === '' || sellxpath === ''
          || unit === '') {
          this.openSnackBar('Please fill all the areas', '');
          this.addedToDB = false;
          this.existingInDB = false;
        } else ...

目前的测试:

it('should reject the bank - unsufficient info', async () => {
const add = new AddBanksComponent(service, snackbar);
add.addBank('Danske Bank', 'DK',
  'http://danskebank.dk', 'DKK',
  'abcdefghijklm', 'abcdefghijklm',
  'abcdefghijklm', '');
console.log('mock ' + add.addedToDB);
console.log('mock ' + add.existingInDB);
await fixture.whenStable();
fixture.detectChanges();
expect(add.addedToDB).toEqual(false);
expect(add.existingInDB).toEqual(false);

2 个答案:

答案 0 :(得分:1)

您需要模拟postBank:

it('should reject the bank - unsufficient info', async () => {
   const add = new AddBanksComponent(service, snackbar);

   const result = ...
   spy = spyOn(add, 'postBank').and.returnValue(result);
   add.addBank('Danske Bank', 'DK','http://danskebank.dk', 'DKK','abcdefghijklm', 'abcdefghijklm','abcdefghijklm', '');

   await fixture.whenStable();
   fixture.detectChanges();
   expect(add.addedToDB).toEqual(false);
   expect(add.existingInDB).toEqual(false);
})

答案 1 :(得分:0)

该服务是一个外部类,可以/应该完全模拟。

const data = // whatever you want the subscribe to pass through

// Create an object that will mock the subscribe
const obsMock = jamsine.createSpyObj('obsMock', ['subscribe'];

// Subscribe is a function that takes a callback. We have to mock that here
obsMock.subscribe.and.callFake((callback) => {
  callback(data);
});

// Create a service spy
const service = jasmine.createSpyObj('service', ['postBank']);

// Have the service.postBank method call return our mocked observable
service.postBank.and.returnValue(obsMock)

// Pass in the mocked service
const add = new AddBanksComponent(service, snackbar);

add.addBank('Danske Bank', 'DK',
   'http://danskebank.dk', 'DKK',
   'abcdefghijklm', 'abcdefghijklm',
   'abcdefghijklm', '');

...verify here