Reputation: 139
I have the following method and I need to do the testing while using Jasmine and Karma. As far as I know it is the subscribe
that does not execute. During the testing variables addedToDB
and existingInDB
are not updated and my testing wants to assert that they are 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 ...
The testing for now:
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);
Upvotes: 0
Views: 100
Reputation: 2339
The service is an external class and can/should be mocked entirely.
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
Upvotes: 0
Reputation: 6821
You need to mock 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);
})
Upvotes: 1