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



我有以下方法,我需要在使用Jasmine和Karma的同时进行测试。据我所知,是subscribe没有执行。在测试过程中,变量addedToDBexistingInDB没有更新,我的测试想要断言它们是false。

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

您需要模拟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);
})

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

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

最新更新