how to mock out an Observable? I have tried to mock it out three different ways Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!What's the difference between faking, mocking, and stubbing?How to make mock to void methods with mockitoDifference between @Mock and @InjectMocksWhat is the difference between Promises and Observables?Angular2 NgModel not getting value in Jasmine testAngular - Karma - ngrx - No provider for Storeangular 5 testing - configure testbed globallyHow to mock @select in Angular 2+Karma error: Cannot set property 'beforePreactivation' of undefinedHow to mock @Select in ngxs when using a mock store
Can I ask an author to send me his ebook?
Who can become a wight?
Can the van der Waals coefficients be negative in the van der Waals equation for real gases?
If gravity precedes the formation of a solar system, where did the mass come from that caused the gravity?
What documents does someone with a long-term visa need to travel to another Schengen country?
Raising a bilingual kid. When should we introduce the majority language?
Where is Bhagavad Gita referred to as Hari Gita?
Why does my GNOME settings mention "Moto C Plus"?
A journey... into the MIND
Can a Wizard take the Magic Initiate feat and select spells from the Wizard list?
Why does BitLocker not use RSA?
Kepler's 3rd law: ratios don't fit data
Normal Operator || T^2|| = ||T||^2
Sorting the characters in a utf-16 string in java
When speaking, how do you change your mind mid-sentence?
How to leave only the following strings?
A German immigrant ancestor has a "Registration Affidavit of Alien Enemy" on file. What does that mean exactly?
“Since the train was delayed for more than an hour, passengers were given a full refund.” – Why is there no article before “passengers”?
Lights are flickering on and off after accidentally bumping into light switch
How to mute a string and play another at the same time
Why doesn't the university give past final exams' answers?
Proving inequality for positive definite matrix
Coin Game with infinite paradox
2 sample t test for sample sizes - 30,000 and 150,000
how to mock out an Observable? I have tried to mock it out three different ways
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!What's the difference between faking, mocking, and stubbing?How to make mock to void methods with mockitoDifference between @Mock and @InjectMocksWhat is the difference between Promises and Observables?Angular2 NgModel not getting value in Jasmine testAngular - Karma - ngrx - No provider for Storeangular 5 testing - configure testbed globallyHow to mock @select in Angular 2+Karma error: Cannot set property 'beforePreactivation' of undefinedHow to mock @Select in ngxs when using a mock store
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I have written many unit tests to test observables, but for some reason, this test is not working like the other ones I've written, but I dont see what the issue is.
I would like a mock for ChangePasswordFacade.successful$ to return an Observable that returns true. Even though I have previously used the mocking strategy below, it's not working. I tried injecting ChangePasswordFacade into the test. I tried using a mock successful$ function in the useValue of the TestBed provider. And I tried the approach below. They all yield sucessful$ as false. How can I mock this out differently to return true?
import ComponentFixture, TestBed from '@angular/core/testing';
import PasswordChangeModalComponent from './password-change-modal.component';
import ReactiveFormsModule from '@angular/forms';
import PasswordChangeFormComponent from '../../..';
import DefaultPopoverComponent from '@bis-angular/shared-components/pattern-library';
import Store, StoreModule from '@ngrx/store';
import
ChangePasswordFacade,
UserInformationFacade,
changePasswordInitialState,
CHANGEPASSWORD_FEATURE_KEY,
changePasswordReducer
from '@bis-angular/users';
import configureTestSuite from 'ng-bullet';
import of from 'rxjs';
describe('PasswordChangeModalComponent', () =>
let component: PasswordChangeModalComponent;
let fixture: ComponentFixture<PasswordChangeModalComponent>;
const childDefaultPopoverComponent = jasmine.createSpyObj('DefaultPopoverComponent', ['hideModal', 'showModal']);
const childPasswordChangeFormComponent = jasmine.createSpyObj('PasswordChangeFormComponent', ['setFormControlsToEmpty']);
const changePasswordFacadeSpy = jasmine.createSpyObj('ChangePasswordFacade', ['resetState']);
configureTestSuite(() =>
TestBed.configureTestingModule(
imports: [
ReactiveFormsModule,
StoreModule.forRoot(),
StoreModule.forFeature(CHANGEPASSWORD_FEATURE_KEY, changePasswordReducer,
initialState: changePasswordInitialState
)
],
declarations: [PasswordChangeFormComponent, DefaultPopoverComponent, PasswordChangeModalComponent],
providers: [Store, UserInformationFacade, ChangePasswordFacade]
);
);
beforeEach(() =>
fixture = TestBed.createComponent(PasswordChangeModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.defaultPopoverComponent = childDefaultPopoverComponent;
component.watchSuccessful = unsubscribe: () => ;
spyOn(component.watchSuccessful, 'unsubscribe');
const service = TestBed.get(ChangePasswordFacade);
spyOn(service, 'successful$').and.returnValue(of(true));
);
describe('showPasswordChangeModal function ', () =>
it('should call showModal and then not hide if not successful ', () =>
spyOn(component, 'hidePasswordChangeModal');
component.successful$.subscribe((successful: boolean) =>
expect(component.hidePasswordChangeModal).toHaveBeenCalled();
expect(changePasswordFacadeSpy.resetState).toHaveBeenCalled();
expect(component.watchSuccessful.unsubscribe).toHaveBeenCalled();
);
component.showPasswordChangeModal();
expect(childDefaultPopoverComponent.showModal).toHaveBeenCalled();
);
);
);
import Injectable from '@angular/core';
import select, Store from '@ngrx/store';
import ChangePasswordPartialState from './change-password.reducer';
import changePasswordQuery from './change-password.selectors';
import ChangePassword, ChangePasswordResetState from './change-password.actions';
import NewPassword from '@bis-angular/users';
@Injectable()
export class ChangePasswordFacade
successful$ = this.store.pipe(select(changePasswordQuery.getSuccessful));
initiated$ = this.store.pipe(select(changePasswordQuery.getInitiated));
constructor(private store: Store<ChangePasswordPartialState>)
changePassword(newPassword: NewPassword, userId: string)
this.store.dispatch(new ChangePassword(newPassword, userId));
resetState()
this.store.dispatch(new ChangePasswordResetState());
angular unit-testing karma-jasmine rxjs6
add a comment |
I have written many unit tests to test observables, but for some reason, this test is not working like the other ones I've written, but I dont see what the issue is.
I would like a mock for ChangePasswordFacade.successful$ to return an Observable that returns true. Even though I have previously used the mocking strategy below, it's not working. I tried injecting ChangePasswordFacade into the test. I tried using a mock successful$ function in the useValue of the TestBed provider. And I tried the approach below. They all yield sucessful$ as false. How can I mock this out differently to return true?
import ComponentFixture, TestBed from '@angular/core/testing';
import PasswordChangeModalComponent from './password-change-modal.component';
import ReactiveFormsModule from '@angular/forms';
import PasswordChangeFormComponent from '../../..';
import DefaultPopoverComponent from '@bis-angular/shared-components/pattern-library';
import Store, StoreModule from '@ngrx/store';
import
ChangePasswordFacade,
UserInformationFacade,
changePasswordInitialState,
CHANGEPASSWORD_FEATURE_KEY,
changePasswordReducer
from '@bis-angular/users';
import configureTestSuite from 'ng-bullet';
import of from 'rxjs';
describe('PasswordChangeModalComponent', () =>
let component: PasswordChangeModalComponent;
let fixture: ComponentFixture<PasswordChangeModalComponent>;
const childDefaultPopoverComponent = jasmine.createSpyObj('DefaultPopoverComponent', ['hideModal', 'showModal']);
const childPasswordChangeFormComponent = jasmine.createSpyObj('PasswordChangeFormComponent', ['setFormControlsToEmpty']);
const changePasswordFacadeSpy = jasmine.createSpyObj('ChangePasswordFacade', ['resetState']);
configureTestSuite(() =>
TestBed.configureTestingModule(
imports: [
ReactiveFormsModule,
StoreModule.forRoot(),
StoreModule.forFeature(CHANGEPASSWORD_FEATURE_KEY, changePasswordReducer,
initialState: changePasswordInitialState
)
],
declarations: [PasswordChangeFormComponent, DefaultPopoverComponent, PasswordChangeModalComponent],
providers: [Store, UserInformationFacade, ChangePasswordFacade]
);
);
beforeEach(() =>
fixture = TestBed.createComponent(PasswordChangeModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.defaultPopoverComponent = childDefaultPopoverComponent;
component.watchSuccessful = unsubscribe: () => ;
spyOn(component.watchSuccessful, 'unsubscribe');
const service = TestBed.get(ChangePasswordFacade);
spyOn(service, 'successful$').and.returnValue(of(true));
);
describe('showPasswordChangeModal function ', () =>
it('should call showModal and then not hide if not successful ', () =>
spyOn(component, 'hidePasswordChangeModal');
component.successful$.subscribe((successful: boolean) =>
expect(component.hidePasswordChangeModal).toHaveBeenCalled();
expect(changePasswordFacadeSpy.resetState).toHaveBeenCalled();
expect(component.watchSuccessful.unsubscribe).toHaveBeenCalled();
);
component.showPasswordChangeModal();
expect(childDefaultPopoverComponent.showModal).toHaveBeenCalled();
);
);
);
import Injectable from '@angular/core';
import select, Store from '@ngrx/store';
import ChangePasswordPartialState from './change-password.reducer';
import changePasswordQuery from './change-password.selectors';
import ChangePassword, ChangePasswordResetState from './change-password.actions';
import NewPassword from '@bis-angular/users';
@Injectable()
export class ChangePasswordFacade
successful$ = this.store.pipe(select(changePasswordQuery.getSuccessful));
initiated$ = this.store.pipe(select(changePasswordQuery.getInitiated));
constructor(private store: Store<ChangePasswordPartialState>)
changePassword(newPassword: NewPassword, userId: string)
this.store.dispatch(new ChangePassword(newPassword, userId));
resetState()
this.store.dispatch(new ChangePasswordResetState());
angular unit-testing karma-jasmine rxjs6
Are you by any chance declaringChangePasswordFacade
in the providers array of the@Component
decorator for the class definition ofPasswordChangeModalComponent
? If so, you'll need to use overrideComponent to successfully inject a mock provider.
– dmcgrandle
Mar 9 at 5:22
add a comment |
I have written many unit tests to test observables, but for some reason, this test is not working like the other ones I've written, but I dont see what the issue is.
I would like a mock for ChangePasswordFacade.successful$ to return an Observable that returns true. Even though I have previously used the mocking strategy below, it's not working. I tried injecting ChangePasswordFacade into the test. I tried using a mock successful$ function in the useValue of the TestBed provider. And I tried the approach below. They all yield sucessful$ as false. How can I mock this out differently to return true?
import ComponentFixture, TestBed from '@angular/core/testing';
import PasswordChangeModalComponent from './password-change-modal.component';
import ReactiveFormsModule from '@angular/forms';
import PasswordChangeFormComponent from '../../..';
import DefaultPopoverComponent from '@bis-angular/shared-components/pattern-library';
import Store, StoreModule from '@ngrx/store';
import
ChangePasswordFacade,
UserInformationFacade,
changePasswordInitialState,
CHANGEPASSWORD_FEATURE_KEY,
changePasswordReducer
from '@bis-angular/users';
import configureTestSuite from 'ng-bullet';
import of from 'rxjs';
describe('PasswordChangeModalComponent', () =>
let component: PasswordChangeModalComponent;
let fixture: ComponentFixture<PasswordChangeModalComponent>;
const childDefaultPopoverComponent = jasmine.createSpyObj('DefaultPopoverComponent', ['hideModal', 'showModal']);
const childPasswordChangeFormComponent = jasmine.createSpyObj('PasswordChangeFormComponent', ['setFormControlsToEmpty']);
const changePasswordFacadeSpy = jasmine.createSpyObj('ChangePasswordFacade', ['resetState']);
configureTestSuite(() =>
TestBed.configureTestingModule(
imports: [
ReactiveFormsModule,
StoreModule.forRoot(),
StoreModule.forFeature(CHANGEPASSWORD_FEATURE_KEY, changePasswordReducer,
initialState: changePasswordInitialState
)
],
declarations: [PasswordChangeFormComponent, DefaultPopoverComponent, PasswordChangeModalComponent],
providers: [Store, UserInformationFacade, ChangePasswordFacade]
);
);
beforeEach(() =>
fixture = TestBed.createComponent(PasswordChangeModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.defaultPopoverComponent = childDefaultPopoverComponent;
component.watchSuccessful = unsubscribe: () => ;
spyOn(component.watchSuccessful, 'unsubscribe');
const service = TestBed.get(ChangePasswordFacade);
spyOn(service, 'successful$').and.returnValue(of(true));
);
describe('showPasswordChangeModal function ', () =>
it('should call showModal and then not hide if not successful ', () =>
spyOn(component, 'hidePasswordChangeModal');
component.successful$.subscribe((successful: boolean) =>
expect(component.hidePasswordChangeModal).toHaveBeenCalled();
expect(changePasswordFacadeSpy.resetState).toHaveBeenCalled();
expect(component.watchSuccessful.unsubscribe).toHaveBeenCalled();
);
component.showPasswordChangeModal();
expect(childDefaultPopoverComponent.showModal).toHaveBeenCalled();
);
);
);
import Injectable from '@angular/core';
import select, Store from '@ngrx/store';
import ChangePasswordPartialState from './change-password.reducer';
import changePasswordQuery from './change-password.selectors';
import ChangePassword, ChangePasswordResetState from './change-password.actions';
import NewPassword from '@bis-angular/users';
@Injectable()
export class ChangePasswordFacade
successful$ = this.store.pipe(select(changePasswordQuery.getSuccessful));
initiated$ = this.store.pipe(select(changePasswordQuery.getInitiated));
constructor(private store: Store<ChangePasswordPartialState>)
changePassword(newPassword: NewPassword, userId: string)
this.store.dispatch(new ChangePassword(newPassword, userId));
resetState()
this.store.dispatch(new ChangePasswordResetState());
angular unit-testing karma-jasmine rxjs6
I have written many unit tests to test observables, but for some reason, this test is not working like the other ones I've written, but I dont see what the issue is.
I would like a mock for ChangePasswordFacade.successful$ to return an Observable that returns true. Even though I have previously used the mocking strategy below, it's not working. I tried injecting ChangePasswordFacade into the test. I tried using a mock successful$ function in the useValue of the TestBed provider. And I tried the approach below. They all yield sucessful$ as false. How can I mock this out differently to return true?
import ComponentFixture, TestBed from '@angular/core/testing';
import PasswordChangeModalComponent from './password-change-modal.component';
import ReactiveFormsModule from '@angular/forms';
import PasswordChangeFormComponent from '../../..';
import DefaultPopoverComponent from '@bis-angular/shared-components/pattern-library';
import Store, StoreModule from '@ngrx/store';
import
ChangePasswordFacade,
UserInformationFacade,
changePasswordInitialState,
CHANGEPASSWORD_FEATURE_KEY,
changePasswordReducer
from '@bis-angular/users';
import configureTestSuite from 'ng-bullet';
import of from 'rxjs';
describe('PasswordChangeModalComponent', () =>
let component: PasswordChangeModalComponent;
let fixture: ComponentFixture<PasswordChangeModalComponent>;
const childDefaultPopoverComponent = jasmine.createSpyObj('DefaultPopoverComponent', ['hideModal', 'showModal']);
const childPasswordChangeFormComponent = jasmine.createSpyObj('PasswordChangeFormComponent', ['setFormControlsToEmpty']);
const changePasswordFacadeSpy = jasmine.createSpyObj('ChangePasswordFacade', ['resetState']);
configureTestSuite(() =>
TestBed.configureTestingModule(
imports: [
ReactiveFormsModule,
StoreModule.forRoot(),
StoreModule.forFeature(CHANGEPASSWORD_FEATURE_KEY, changePasswordReducer,
initialState: changePasswordInitialState
)
],
declarations: [PasswordChangeFormComponent, DefaultPopoverComponent, PasswordChangeModalComponent],
providers: [Store, UserInformationFacade, ChangePasswordFacade]
);
);
beforeEach(() =>
fixture = TestBed.createComponent(PasswordChangeModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.defaultPopoverComponent = childDefaultPopoverComponent;
component.watchSuccessful = unsubscribe: () => ;
spyOn(component.watchSuccessful, 'unsubscribe');
const service = TestBed.get(ChangePasswordFacade);
spyOn(service, 'successful$').and.returnValue(of(true));
);
describe('showPasswordChangeModal function ', () =>
it('should call showModal and then not hide if not successful ', () =>
spyOn(component, 'hidePasswordChangeModal');
component.successful$.subscribe((successful: boolean) =>
expect(component.hidePasswordChangeModal).toHaveBeenCalled();
expect(changePasswordFacadeSpy.resetState).toHaveBeenCalled();
expect(component.watchSuccessful.unsubscribe).toHaveBeenCalled();
);
component.showPasswordChangeModal();
expect(childDefaultPopoverComponent.showModal).toHaveBeenCalled();
);
);
);
import Injectable from '@angular/core';
import select, Store from '@ngrx/store';
import ChangePasswordPartialState from './change-password.reducer';
import changePasswordQuery from './change-password.selectors';
import ChangePassword, ChangePasswordResetState from './change-password.actions';
import NewPassword from '@bis-angular/users';
@Injectable()
export class ChangePasswordFacade
successful$ = this.store.pipe(select(changePasswordQuery.getSuccessful));
initiated$ = this.store.pipe(select(changePasswordQuery.getInitiated));
constructor(private store: Store<ChangePasswordPartialState>)
changePassword(newPassword: NewPassword, userId: string)
this.store.dispatch(new ChangePassword(newPassword, userId));
resetState()
this.store.dispatch(new ChangePasswordResetState());
angular unit-testing karma-jasmine rxjs6
angular unit-testing karma-jasmine rxjs6
edited Mar 9 at 4:26
user372225
asked Mar 9 at 2:47
user372225user372225
314419
314419
Are you by any chance declaringChangePasswordFacade
in the providers array of the@Component
decorator for the class definition ofPasswordChangeModalComponent
? If so, you'll need to use overrideComponent to successfully inject a mock provider.
– dmcgrandle
Mar 9 at 5:22
add a comment |
Are you by any chance declaringChangePasswordFacade
in the providers array of the@Component
decorator for the class definition ofPasswordChangeModalComponent
? If so, you'll need to use overrideComponent to successfully inject a mock provider.
– dmcgrandle
Mar 9 at 5:22
Are you by any chance declaring
ChangePasswordFacade
in the providers array of the @Component
decorator for the class definition of PasswordChangeModalComponent
? If so, you'll need to use overrideComponent to successfully inject a mock provider.– dmcgrandle
Mar 9 at 5:22
Are you by any chance declaring
ChangePasswordFacade
in the providers array of the @Component
decorator for the class definition of PasswordChangeModalComponent
? If so, you'll need to use overrideComponent to successfully inject a mock provider.– dmcgrandle
Mar 9 at 5:22
add a comment |
2 Answers
2
active
oldest
votes
here is how I did it: I used the store to dispatch an action to change successful$ to true. it's now an integration test at this point, not a unit test.
import ChangePasswordFacade, UserInformationFacade from '@bis-angular/users';
import ComponentFixture, TestBed from '@angular/core/testing';
import StoreModule, Store from '@ngrx/store';
import PasswordChangeModalComponent, PasswordChangeFormComponent from '../../..';
import * as fromFeature from '@bis-angular/users';
import ReactiveFormsModule from '@angular/forms';
import configureTestSuite from 'ng-bullet';
import DefaultPopoverComponent from '@bis-angular/shared-components/pattern-library';
describe('PasswordChangeModalComponent', () =>
let component: PasswordChangeModalComponent;
let fixture: ComponentFixture<PasswordChangeModalComponent>;
let store: Store<fromFeature.ChangePasswordState>;
const childDefaultPopoverComponent = jasmine.createSpyObj('DefaultPopoverComponent', ['hideModal', 'showModal']);
const childPasswordChangeFormComponent = jasmine.createSpyObj('PasswordChangeFormComponent', ['setFormControlsToEmpty']);
configureTestSuite(() =>
TestBed.configureTestingModule(
imports: [
StoreModule.forRoot(),
ReactiveFormsModule,
StoreModule.forFeature(fromFeature.CHANGEPASSWORD_FEATURE_KEY, fromFeature.changePasswordReducer,
initialState: fromFeature.changePasswordInitialState
)
],
declarations: [PasswordChangeModalComponent, DefaultPopoverComponent, PasswordChangeFormComponent],
providers: [ChangePasswordFacade, UserInformationFacade]
);
);
beforeEach(() =>
store = TestBed.get(Store);
spyOn(store, 'dispatch').and.callThrough();
fixture = TestBed.createComponent(PasswordChangeModalComponent);
component = fixture.componentInstance;
component.defaultPopoverComponent = childDefaultPopoverComponent;
component.watchSuccessful = unsubscribe: () => ;
spyOn(component.watchSuccessful, 'unsubscribe');
fixture.detectChanges();
);
it('should be created', () =>
expect(component).toBeTruthy();
);
describe('showPasswordChangeModal function ', () =>
it('should call showModal and then hide if successful ', () =>
spyOn(component, 'hidePasswordChangeModal');
spyOn(component.changePasswordService, 'resetState');
const action = new fromFeature.ChangePasswordSuccessful();
store.dispatch(action);
component.showPasswordChangeModal();
component.successful$.subscribe((successful: boolean) =>
expect(component.hidePasswordChangeModal).toHaveBeenCalled();
expect(component.changePasswordService.resetState).toHaveBeenCalled();
);
expect(childDefaultPopoverComponent.showModal).toHaveBeenCalled();
);
);
);
add a comment |
Since, you want to access successful$
which is defined at class level of ChangePasswordFacade
.
something like:
export class ChangePasswordFacade
successful$:observable // ... something like this
You should try useValue
:
configureTestSuite(() =>
TestBed.configureTestingModule(
imports: [
ReactiveFormsModule,
StoreModule.forRoot(),
StoreModule.forFeature(CHANGEPASSWORD_FEATURE_KEY, changePasswordReducer,
initialState: changePasswordInitialState
)
],
declarations: [PasswordChangeFormComponent, DefaultPopoverComponent, PasswordChangeModalComponent],
providers: [Store, UserInformationFacade,
provide: ChangePasswordFacade , useValue:
successful$ : of(true)
'
]
);
);
thank you for the suggestion. I tried the exact approach you suggested above, as I noted in my initial problem description. It did not work.
– user372225
Mar 9 at 4:23
@user372225 : what values did you get fromsucceessful$
when u tried my suggestion ?
– Shashank Vivek
Mar 9 at 5:37
hi @ShashankVivek, I get 'false' value for successful$ using your suggestion.
– user372225
Mar 11 at 13:48
@user372225 even when you are setting setting itof(true)
true
? some variable seems to manipulating it then
– Shashank Vivek
Mar 12 at 4:58
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55073535%2fhow-to-mock-out-an-observable-i-have-tried-to-mock-it-out-three-different-ways%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
here is how I did it: I used the store to dispatch an action to change successful$ to true. it's now an integration test at this point, not a unit test.
import ChangePasswordFacade, UserInformationFacade from '@bis-angular/users';
import ComponentFixture, TestBed from '@angular/core/testing';
import StoreModule, Store from '@ngrx/store';
import PasswordChangeModalComponent, PasswordChangeFormComponent from '../../..';
import * as fromFeature from '@bis-angular/users';
import ReactiveFormsModule from '@angular/forms';
import configureTestSuite from 'ng-bullet';
import DefaultPopoverComponent from '@bis-angular/shared-components/pattern-library';
describe('PasswordChangeModalComponent', () =>
let component: PasswordChangeModalComponent;
let fixture: ComponentFixture<PasswordChangeModalComponent>;
let store: Store<fromFeature.ChangePasswordState>;
const childDefaultPopoverComponent = jasmine.createSpyObj('DefaultPopoverComponent', ['hideModal', 'showModal']);
const childPasswordChangeFormComponent = jasmine.createSpyObj('PasswordChangeFormComponent', ['setFormControlsToEmpty']);
configureTestSuite(() =>
TestBed.configureTestingModule(
imports: [
StoreModule.forRoot(),
ReactiveFormsModule,
StoreModule.forFeature(fromFeature.CHANGEPASSWORD_FEATURE_KEY, fromFeature.changePasswordReducer,
initialState: fromFeature.changePasswordInitialState
)
],
declarations: [PasswordChangeModalComponent, DefaultPopoverComponent, PasswordChangeFormComponent],
providers: [ChangePasswordFacade, UserInformationFacade]
);
);
beforeEach(() =>
store = TestBed.get(Store);
spyOn(store, 'dispatch').and.callThrough();
fixture = TestBed.createComponent(PasswordChangeModalComponent);
component = fixture.componentInstance;
component.defaultPopoverComponent = childDefaultPopoverComponent;
component.watchSuccessful = unsubscribe: () => ;
spyOn(component.watchSuccessful, 'unsubscribe');
fixture.detectChanges();
);
it('should be created', () =>
expect(component).toBeTruthy();
);
describe('showPasswordChangeModal function ', () =>
it('should call showModal and then hide if successful ', () =>
spyOn(component, 'hidePasswordChangeModal');
spyOn(component.changePasswordService, 'resetState');
const action = new fromFeature.ChangePasswordSuccessful();
store.dispatch(action);
component.showPasswordChangeModal();
component.successful$.subscribe((successful: boolean) =>
expect(component.hidePasswordChangeModal).toHaveBeenCalled();
expect(component.changePasswordService.resetState).toHaveBeenCalled();
);
expect(childDefaultPopoverComponent.showModal).toHaveBeenCalled();
);
);
);
add a comment |
here is how I did it: I used the store to dispatch an action to change successful$ to true. it's now an integration test at this point, not a unit test.
import ChangePasswordFacade, UserInformationFacade from '@bis-angular/users';
import ComponentFixture, TestBed from '@angular/core/testing';
import StoreModule, Store from '@ngrx/store';
import PasswordChangeModalComponent, PasswordChangeFormComponent from '../../..';
import * as fromFeature from '@bis-angular/users';
import ReactiveFormsModule from '@angular/forms';
import configureTestSuite from 'ng-bullet';
import DefaultPopoverComponent from '@bis-angular/shared-components/pattern-library';
describe('PasswordChangeModalComponent', () =>
let component: PasswordChangeModalComponent;
let fixture: ComponentFixture<PasswordChangeModalComponent>;
let store: Store<fromFeature.ChangePasswordState>;
const childDefaultPopoverComponent = jasmine.createSpyObj('DefaultPopoverComponent', ['hideModal', 'showModal']);
const childPasswordChangeFormComponent = jasmine.createSpyObj('PasswordChangeFormComponent', ['setFormControlsToEmpty']);
configureTestSuite(() =>
TestBed.configureTestingModule(
imports: [
StoreModule.forRoot(),
ReactiveFormsModule,
StoreModule.forFeature(fromFeature.CHANGEPASSWORD_FEATURE_KEY, fromFeature.changePasswordReducer,
initialState: fromFeature.changePasswordInitialState
)
],
declarations: [PasswordChangeModalComponent, DefaultPopoverComponent, PasswordChangeFormComponent],
providers: [ChangePasswordFacade, UserInformationFacade]
);
);
beforeEach(() =>
store = TestBed.get(Store);
spyOn(store, 'dispatch').and.callThrough();
fixture = TestBed.createComponent(PasswordChangeModalComponent);
component = fixture.componentInstance;
component.defaultPopoverComponent = childDefaultPopoverComponent;
component.watchSuccessful = unsubscribe: () => ;
spyOn(component.watchSuccessful, 'unsubscribe');
fixture.detectChanges();
);
it('should be created', () =>
expect(component).toBeTruthy();
);
describe('showPasswordChangeModal function ', () =>
it('should call showModal and then hide if successful ', () =>
spyOn(component, 'hidePasswordChangeModal');
spyOn(component.changePasswordService, 'resetState');
const action = new fromFeature.ChangePasswordSuccessful();
store.dispatch(action);
component.showPasswordChangeModal();
component.successful$.subscribe((successful: boolean) =>
expect(component.hidePasswordChangeModal).toHaveBeenCalled();
expect(component.changePasswordService.resetState).toHaveBeenCalled();
);
expect(childDefaultPopoverComponent.showModal).toHaveBeenCalled();
);
);
);
add a comment |
here is how I did it: I used the store to dispatch an action to change successful$ to true. it's now an integration test at this point, not a unit test.
import ChangePasswordFacade, UserInformationFacade from '@bis-angular/users';
import ComponentFixture, TestBed from '@angular/core/testing';
import StoreModule, Store from '@ngrx/store';
import PasswordChangeModalComponent, PasswordChangeFormComponent from '../../..';
import * as fromFeature from '@bis-angular/users';
import ReactiveFormsModule from '@angular/forms';
import configureTestSuite from 'ng-bullet';
import DefaultPopoverComponent from '@bis-angular/shared-components/pattern-library';
describe('PasswordChangeModalComponent', () =>
let component: PasswordChangeModalComponent;
let fixture: ComponentFixture<PasswordChangeModalComponent>;
let store: Store<fromFeature.ChangePasswordState>;
const childDefaultPopoverComponent = jasmine.createSpyObj('DefaultPopoverComponent', ['hideModal', 'showModal']);
const childPasswordChangeFormComponent = jasmine.createSpyObj('PasswordChangeFormComponent', ['setFormControlsToEmpty']);
configureTestSuite(() =>
TestBed.configureTestingModule(
imports: [
StoreModule.forRoot(),
ReactiveFormsModule,
StoreModule.forFeature(fromFeature.CHANGEPASSWORD_FEATURE_KEY, fromFeature.changePasswordReducer,
initialState: fromFeature.changePasswordInitialState
)
],
declarations: [PasswordChangeModalComponent, DefaultPopoverComponent, PasswordChangeFormComponent],
providers: [ChangePasswordFacade, UserInformationFacade]
);
);
beforeEach(() =>
store = TestBed.get(Store);
spyOn(store, 'dispatch').and.callThrough();
fixture = TestBed.createComponent(PasswordChangeModalComponent);
component = fixture.componentInstance;
component.defaultPopoverComponent = childDefaultPopoverComponent;
component.watchSuccessful = unsubscribe: () => ;
spyOn(component.watchSuccessful, 'unsubscribe');
fixture.detectChanges();
);
it('should be created', () =>
expect(component).toBeTruthy();
);
describe('showPasswordChangeModal function ', () =>
it('should call showModal and then hide if successful ', () =>
spyOn(component, 'hidePasswordChangeModal');
spyOn(component.changePasswordService, 'resetState');
const action = new fromFeature.ChangePasswordSuccessful();
store.dispatch(action);
component.showPasswordChangeModal();
component.successful$.subscribe((successful: boolean) =>
expect(component.hidePasswordChangeModal).toHaveBeenCalled();
expect(component.changePasswordService.resetState).toHaveBeenCalled();
);
expect(childDefaultPopoverComponent.showModal).toHaveBeenCalled();
);
);
);
here is how I did it: I used the store to dispatch an action to change successful$ to true. it's now an integration test at this point, not a unit test.
import ChangePasswordFacade, UserInformationFacade from '@bis-angular/users';
import ComponentFixture, TestBed from '@angular/core/testing';
import StoreModule, Store from '@ngrx/store';
import PasswordChangeModalComponent, PasswordChangeFormComponent from '../../..';
import * as fromFeature from '@bis-angular/users';
import ReactiveFormsModule from '@angular/forms';
import configureTestSuite from 'ng-bullet';
import DefaultPopoverComponent from '@bis-angular/shared-components/pattern-library';
describe('PasswordChangeModalComponent', () =>
let component: PasswordChangeModalComponent;
let fixture: ComponentFixture<PasswordChangeModalComponent>;
let store: Store<fromFeature.ChangePasswordState>;
const childDefaultPopoverComponent = jasmine.createSpyObj('DefaultPopoverComponent', ['hideModal', 'showModal']);
const childPasswordChangeFormComponent = jasmine.createSpyObj('PasswordChangeFormComponent', ['setFormControlsToEmpty']);
configureTestSuite(() =>
TestBed.configureTestingModule(
imports: [
StoreModule.forRoot(),
ReactiveFormsModule,
StoreModule.forFeature(fromFeature.CHANGEPASSWORD_FEATURE_KEY, fromFeature.changePasswordReducer,
initialState: fromFeature.changePasswordInitialState
)
],
declarations: [PasswordChangeModalComponent, DefaultPopoverComponent, PasswordChangeFormComponent],
providers: [ChangePasswordFacade, UserInformationFacade]
);
);
beforeEach(() =>
store = TestBed.get(Store);
spyOn(store, 'dispatch').and.callThrough();
fixture = TestBed.createComponent(PasswordChangeModalComponent);
component = fixture.componentInstance;
component.defaultPopoverComponent = childDefaultPopoverComponent;
component.watchSuccessful = unsubscribe: () => ;
spyOn(component.watchSuccessful, 'unsubscribe');
fixture.detectChanges();
);
it('should be created', () =>
expect(component).toBeTruthy();
);
describe('showPasswordChangeModal function ', () =>
it('should call showModal and then hide if successful ', () =>
spyOn(component, 'hidePasswordChangeModal');
spyOn(component.changePasswordService, 'resetState');
const action = new fromFeature.ChangePasswordSuccessful();
store.dispatch(action);
component.showPasswordChangeModal();
component.successful$.subscribe((successful: boolean) =>
expect(component.hidePasswordChangeModal).toHaveBeenCalled();
expect(component.changePasswordService.resetState).toHaveBeenCalled();
);
expect(childDefaultPopoverComponent.showModal).toHaveBeenCalled();
);
);
);
answered Mar 15 at 17:38
user372225user372225
314419
314419
add a comment |
add a comment |
Since, you want to access successful$
which is defined at class level of ChangePasswordFacade
.
something like:
export class ChangePasswordFacade
successful$:observable // ... something like this
You should try useValue
:
configureTestSuite(() =>
TestBed.configureTestingModule(
imports: [
ReactiveFormsModule,
StoreModule.forRoot(),
StoreModule.forFeature(CHANGEPASSWORD_FEATURE_KEY, changePasswordReducer,
initialState: changePasswordInitialState
)
],
declarations: [PasswordChangeFormComponent, DefaultPopoverComponent, PasswordChangeModalComponent],
providers: [Store, UserInformationFacade,
provide: ChangePasswordFacade , useValue:
successful$ : of(true)
'
]
);
);
thank you for the suggestion. I tried the exact approach you suggested above, as I noted in my initial problem description. It did not work.
– user372225
Mar 9 at 4:23
@user372225 : what values did you get fromsucceessful$
when u tried my suggestion ?
– Shashank Vivek
Mar 9 at 5:37
hi @ShashankVivek, I get 'false' value for successful$ using your suggestion.
– user372225
Mar 11 at 13:48
@user372225 even when you are setting setting itof(true)
true
? some variable seems to manipulating it then
– Shashank Vivek
Mar 12 at 4:58
add a comment |
Since, you want to access successful$
which is defined at class level of ChangePasswordFacade
.
something like:
export class ChangePasswordFacade
successful$:observable // ... something like this
You should try useValue
:
configureTestSuite(() =>
TestBed.configureTestingModule(
imports: [
ReactiveFormsModule,
StoreModule.forRoot(),
StoreModule.forFeature(CHANGEPASSWORD_FEATURE_KEY, changePasswordReducer,
initialState: changePasswordInitialState
)
],
declarations: [PasswordChangeFormComponent, DefaultPopoverComponent, PasswordChangeModalComponent],
providers: [Store, UserInformationFacade,
provide: ChangePasswordFacade , useValue:
successful$ : of(true)
'
]
);
);
thank you for the suggestion. I tried the exact approach you suggested above, as I noted in my initial problem description. It did not work.
– user372225
Mar 9 at 4:23
@user372225 : what values did you get fromsucceessful$
when u tried my suggestion ?
– Shashank Vivek
Mar 9 at 5:37
hi @ShashankVivek, I get 'false' value for successful$ using your suggestion.
– user372225
Mar 11 at 13:48
@user372225 even when you are setting setting itof(true)
true
? some variable seems to manipulating it then
– Shashank Vivek
Mar 12 at 4:58
add a comment |
Since, you want to access successful$
which is defined at class level of ChangePasswordFacade
.
something like:
export class ChangePasswordFacade
successful$:observable // ... something like this
You should try useValue
:
configureTestSuite(() =>
TestBed.configureTestingModule(
imports: [
ReactiveFormsModule,
StoreModule.forRoot(),
StoreModule.forFeature(CHANGEPASSWORD_FEATURE_KEY, changePasswordReducer,
initialState: changePasswordInitialState
)
],
declarations: [PasswordChangeFormComponent, DefaultPopoverComponent, PasswordChangeModalComponent],
providers: [Store, UserInformationFacade,
provide: ChangePasswordFacade , useValue:
successful$ : of(true)
'
]
);
);
Since, you want to access successful$
which is defined at class level of ChangePasswordFacade
.
something like:
export class ChangePasswordFacade
successful$:observable // ... something like this
You should try useValue
:
configureTestSuite(() =>
TestBed.configureTestingModule(
imports: [
ReactiveFormsModule,
StoreModule.forRoot(),
StoreModule.forFeature(CHANGEPASSWORD_FEATURE_KEY, changePasswordReducer,
initialState: changePasswordInitialState
)
],
declarations: [PasswordChangeFormComponent, DefaultPopoverComponent, PasswordChangeModalComponent],
providers: [Store, UserInformationFacade,
provide: ChangePasswordFacade , useValue:
successful$ : of(true)
'
]
);
);
answered Mar 9 at 3:50
Shashank VivekShashank Vivek
5,47932463
5,47932463
thank you for the suggestion. I tried the exact approach you suggested above, as I noted in my initial problem description. It did not work.
– user372225
Mar 9 at 4:23
@user372225 : what values did you get fromsucceessful$
when u tried my suggestion ?
– Shashank Vivek
Mar 9 at 5:37
hi @ShashankVivek, I get 'false' value for successful$ using your suggestion.
– user372225
Mar 11 at 13:48
@user372225 even when you are setting setting itof(true)
true
? some variable seems to manipulating it then
– Shashank Vivek
Mar 12 at 4:58
add a comment |
thank you for the suggestion. I tried the exact approach you suggested above, as I noted in my initial problem description. It did not work.
– user372225
Mar 9 at 4:23
@user372225 : what values did you get fromsucceessful$
when u tried my suggestion ?
– Shashank Vivek
Mar 9 at 5:37
hi @ShashankVivek, I get 'false' value for successful$ using your suggestion.
– user372225
Mar 11 at 13:48
@user372225 even when you are setting setting itof(true)
true
? some variable seems to manipulating it then
– Shashank Vivek
Mar 12 at 4:58
thank you for the suggestion. I tried the exact approach you suggested above, as I noted in my initial problem description. It did not work.
– user372225
Mar 9 at 4:23
thank you for the suggestion. I tried the exact approach you suggested above, as I noted in my initial problem description. It did not work.
– user372225
Mar 9 at 4:23
@user372225 : what values did you get from
succeessful$
when u tried my suggestion ?– Shashank Vivek
Mar 9 at 5:37
@user372225 : what values did you get from
succeessful$
when u tried my suggestion ?– Shashank Vivek
Mar 9 at 5:37
hi @ShashankVivek, I get 'false' value for successful$ using your suggestion.
– user372225
Mar 11 at 13:48
hi @ShashankVivek, I get 'false' value for successful$ using your suggestion.
– user372225
Mar 11 at 13:48
@user372225 even when you are setting setting it
of(true)
true
? some variable seems to manipulating it then– Shashank Vivek
Mar 12 at 4:58
@user372225 even when you are setting setting it
of(true)
true
? some variable seems to manipulating it then– Shashank Vivek
Mar 12 at 4:58
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55073535%2fhow-to-mock-out-an-observable-i-have-tried-to-mock-it-out-three-different-ways%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Are you by any chance declaring
ChangePasswordFacade
in the providers array of the@Component
decorator for the class definition ofPasswordChangeModalComponent
? If so, you'll need to use overrideComponent to successfully inject a mock provider.– dmcgrandle
Mar 9 at 5:22