how to mock out an Observable? I have tried to mock it out three different waysWhat'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 the recruiters in my resume to put the reason why I am rejected?
How to test if a transaction is standard without spending real money?
How to say job offer in Mandarin/Cantonese?
Why can't I see bouncing of a switch on an oscilloscope?
Is this a crack on the carbon frame?
How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?
Today is the Center
Is it possible to do 50 km distance without any previous training?
What is the word for reserving something for yourself before others do?
Email Account under attack (really) - anything I can do?
A newer friend of my brother's gave him a load of baseball cards that are supposedly extremely valuable. Is this a scam?
Test whether all array elements are factors of a number
Is it important to consider tone, melody, and musical form while writing a song?
Is it legal for company to use my work email to pretend I still work there?
Risk of getting Chronic Wasting Disease (CWD) in the United States?
How can bays and straits be determined in a procedurally generated map?
What typically incentivizes a professor to change jobs to a lower ranking university?
How can I prevent hyper evolved versions of regular creatures from wiping out their cousins?
How old can references or sources in a thesis be?
Why dont electromagnetic waves interact with each other?
Theorem, big Paralist and Amsart
Do I have a twin with permutated remainders?
Languages that we cannot (dis)prove to be Context-Free
What does CI-V stand for?
how to mock out an Observable? I have tried to mock it out three different ways
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,23832463
5,23832463
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