我有以下方法,我需要在使用Jasmine和Karma时进行测试。据我所知,是subscribe
不会执行的。在测试过程中的变量addedToDB
,并existingInDB
没有更新,我的测试要断言他们是假的。
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);
该服务是一个外部类,可以/应该完全模拟。
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句