angular2: how to test a component which has an observable time interval - unit-testing

I have a slide-show component that has an Input array of slide objects and shows each one as long as it's been defined in slide.time of itself. also there are two buttons that clicking them has to slide to the next item and reset the timer. in order to make this work, I'm using Observables like this:
/**
* a "SUBJECT" for pausing(restarting) the slider's auto-slide on user's click on left and right arrows
* #type {Subject}
*/
private pauser = new Subject();
/**
* the main observable for timer (before adding the pause/reset option)
* #type {Observable<T>}
*/
private source = Observable
.interval(1000)
.timeInterval()
.map(function (x) { /*return x.value + ':' + x.interval;*/ return x })
.share();
/**
* the final timer, which can be paused
* #type {Observable<R>}
*/
private pausableSource = this.pauser.switchMap(paused => paused ? Observable.never() : this.source);
/**
* the subscription to the timer which is assigned at OnInit hook , and destroyed at OnDestroy
*/
private subscription;
ngOnInit(){
this.subscription = this.pausableSource.subscribe(() => {
//doing changes to the template and changing between slides
});
this.pauser.next(false);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
and it's working properly.
now to test this component, I'm giving it some data within a test-host component and want to check it's functionality like this:
it("should show the second (.slidingImg img) element after testHost.data[0].time seconds
have passed (which here, is 2 seconds)", () => {
//testing
});
i tried many things that i found in docs or anywhere on the internet, but none of them work for me. the problem is that I can't mock the passage of time in a way that the observable timer would perform next actions, and it's like no time has passed whatsoever. two of the ways that haven't worked for me are these:
it("should show the second (.slidingImg img) element after testHost.data[0].time seconds
have passed (which here, is 2 seconds)", fakeAsync(() => {
fixture.detectChanges();
tick(2500);
flushMicrotasks();
fixture.detectChanges();
let secondSlidingImg = fixture.debugElement.queryAll(By.css('.slidingImg'))[1].query(By.css('img'));
expect(secondSlidingImg).toBeTruthy();
//error: expected null to be truthy
}));
i got this from angular2 docs.
and:
beforeEach(() => {
fixture = TestBed.createComponent(TestHostComponent);
testHost = fixture.componentInstance;
scheduler = new TestScheduler((a, b) => expect(a).toEqual(b));
const originalTimer = Observable.interval;
spyOn(Observable, 'interval').and.callFake(function(initialDelay, dueTime) {
return originalTimer.call(this, initialDelay, dueTime, scheduler);
});
// or:
// const originalTimer = Observable.timer;
// spyOn(Observable, 'timer').and.callFake(function(initialDelay, dueTime) {
// return originalTimer.call(this, initialDelay, dueTime, scheduler);
// });
scheduler.maxFrames = 5000;
});
it("should show the second (.slidingImg img) element after testHost.data[0].time seconds
have passed (which here, is 2 seconds)", async(() => {
scheduler.schedule(() => {
fixture.detectChanges();
let secondSlidingImg = fixture.debugElement.queryAll(By.css('.slidingImg'))[1].query(By.css('img'));
expect(secondSlidingImg).toBeTruthy();
//error: expected null to be truthy
}, 2500, null);
scheduler.flush();
}));
i got this approach from this question.
so I desperately need to know how exactly should I simulate time passage in my unit test so that the component's observable time interval would really trigger...
versions:
angular: "2.4.5"
"rxjs": "5.0.1"
"jasmine": "~2.4.1"
"karma": "^1.3.0"
"typescript": "~2.0.10"
"webpack": "2.2.1"

fakeAsync doesn't work for some case with RxJs. You need to manually move internal timer in RxJs. Something along those lines:
import {async} from 'rxjs/internal/scheduler/async';
...
describe('faking internal RxJs scheduler', () => {
let currentTime: number;
beforeEach(() => {
currentTime = 0;
spyOn(async, 'now').and.callFake(() => currentTime);
});
it('testing RxJs delayed execution after 1000ms', fakeAsync(() => {
// Do your stuff
fixture.detectChanges();
currentTime = 1000;
tick(1000);
discardPeriodicTasks();
expect(...);
}));
});

Best way I found for testing this is Marble Testing:
Tutorial: https://medium.com/#bencabanes/marble-testing-observable-introduction-1f5ad39231c
You can control emits by order and time, which seems to be exactly what you need.

Related

How to write unit test with Higher Order Function with Jest in React JS

Hello i'm new to React and i'm trying to write a unit test on a Higher Order Functions with Jest and i don't know how to do it please can someone help me ? This is the code of my HIGHER ORDER FUNCTION below :
const updateSearchTopStoriesState = (hits, page) => (prevState) => {
const { searchKey, results } = prevState
const oldHits = results && results[searchKey]
? results[searchKey].hits
: []
const updatedHits = [
...oldHits,
...hits
]
// returning our previous state
return {
results: {
...results,
[searchKey]: { hits: updatedHits, page }
},
isLoading: false
}
}
export default updateSearchTopStoriesState
Without knowing WHAT you are trying to test, or WHAT the shape of any of the parameters are, this is near impossible to answer accurately. Here are a couple of unit tests I would write:
describe("updateSearchTopStoriesState", () => {
it("should return a function", () => {
expect(typeof updateSearchTopStoriesState()).toBe("function");
});
it("should return default return value", () => {
const { results, isLoading } = updateSearchTopStoriesState()({
searchKey: "test"
});
expect(results).toEqual({ test: { hits: [] } });
expect(isLoading).toBe(false);
});
});
In the sandbox I've started a third test that currently fails (admittedly likely due to my lack of context on the parameters, but should be passing based upon an internal implementation comment you left in the function code).
This should assist you in starting a unit test file for this function, but please comment if anything is unclear or this isn't quite what you are asking about.

How can I unit test a retryWhen operator in rxjs?

I am attempting to unit test a custom RxJS operator. The operator is very simple, it uses RetryWhen to retry a failed HTTP request, but has a delay and will only retry when the HTTP Error is in the 500 range. Using jasmine, and this is in an Angular application.
I've looked at this:
rxjs unit test with retryWhen
Unfortunately, updating the SpyOn call doesn't seem to change the returned observable on successive retries. Each time it retries it is retrying with the original spyon Value.
I have also looked at a bunch of rxjs marble examples, none of which seem to work. I am not sure it is possible to use rxjs marbles here, because (AFAIK) there is no way to simulate a situation where you first submit an errored observable, then submit a successful observable on subsequent tries.
The code is basically a clone of this:
https://blog.angularindepth.com/retry-failed-http-requests-in-angular-f5959d486294
export function delayedRetry(delayMS: number, maxRetry) {
let retries = maxRetry;
return (src: Observable<any>) =>
src.pipe(
retryWhen((errors: Observable<any>) => errors.pipe(
delay(delayMS),
mergeMap(error =>
(retries-- > 0 && error.status >= 500) ? of(error) : throwError(error))
))
);
}
I would like to be able to demonstrate that it can subscribe to an observable that returns an error on the first attempt, but then returns a successful response. The end subscription should show whatever success value the observable emits.
Thank you in advance for any insights.
try use this observable as source observable to test
const source = (called,successAt)=>{
return defer(()=>{
if(called<successAt){
called++
return throwError({status:500})
}
else return of(true)
})
}
test
this.delayedRetry(1000,3)(source(0,3)).subscribe()
To test the retry functionality, you need a observable which emits different events each time you call it. For example:
let alreadyCalled = false;
const spy = spyOn<any>(TestBed.inject(MyService), 'getObservable').and.returnValue(
new Observable((observer) => {
if (alreadyCalled) {
observer.next(message);
}
alreadyCalled = true;
observer.error('error message');
})
);
This observable will emit an error first and after that a next event.
You can check, if your observable got the message like this:
it('should retry on error', async(done) => {
let alreadyCalled = false;
const spy = spyOn<any>(TestBed.inject(MyDependencyService), 'getObservable').and.returnValue(
new Observable((observer) => {
if (alreadyCalled) {
observer.next(message);
}
alreadyCalled = true;
observer.error('error message');
})
);
const observer = {
next: (result) => {
expect(result.value).toBe(expectedResult);
done();
}
}
subscription = service.methodUnderTest(observer);
expect(spy).toHaveBeenCalledTimes(1);
}
Building on a previous answer I have been using this, which gives you more control over what's returned.
const source = (observables) => {
let count = 0;
return defer(() => {
return observables[count++];
});
};
Which can then be used like this
const obsA = source([
throwError({status: 500}),
of(1),
]);
Or it can then be used with rxjs marbles like
const obsA = source([
cold('--#', null, { status: 500 }),
cold('--(a|)', { a: 1 }),
]);

How to mock DialogService.open(...).whenClosed(...) with Jasmine?

We have some TypeScript code using the Aurelia framework and Dialog plugin that we are trying to test with Jasmine, but can't work out how to do properly.
This is the source function:
openDialog(action: string) {
this._dialogService.open({ viewModel: AddAccountWizard })
.whenClosed(result => {
if (!result.wasCancelled && result.output) {
const step = this.steps.find((i) => i.action === action);
if (step) {
step.isCompleted = true;
}
}
});
}
We can create a DialogService spy, and verify the open method easily - but we can't work out how to make the spy invoke the whenClosed method with a mocked result parameter so that we can then assert that the step is completed.
This is the current Jasmine code:
it("opens a dialog when clicking on incomplete bank account", async done => {
// arrange
arrangeMemberVerificationStatus();
await component.create(bootstrap);
const vm = component.viewModel as GettingStartedCustomElement;
dialogService.open.and.callFake(() => {
return { whenClosed: () => Promise.resolve({})};
});
// act
$(".link, .-arrow")[0].click();
// assert
expect(dialogService.open).toHaveBeenCalledWith({ viewModel: AddAccountWizard });
expect(vm.steps[2].isCompleted).toBeTruthy(); // FAILS
done();
});
We've just recently updated our DialogService and ran into the same issue, so we've made this primitive mock that suited our purposes so far. It's fairly limited and doesn't do well for mocking multiple calls with different results, but should work for your above case:
export class DialogServiceMock {
shouldCancelDialog = false;
leaveDialogOpen = false;
desiredOutput = {};
open = () => {
let result = { wasCancelled: this.shouldCancelDialog, output: this.desiredOutput };
let closedPromise = this.leaveDialogOpen ? new Promise((r) => { }) : Promise.resolve(result);
let resultPromise = Promise.resolve({ closeResult: closedPromise });
resultPromise.whenClosed = (callback) => {
return this.leaveDialogOpen ? new Promise((r) => { }) : Promise.resolve(typeof callback == "function" ? callback(result) : null);
};
return resultPromise;
};
}
This mock can be configured to test various responses, when a user cancels the dialog, and scenarios where the dialog is still open.
We haven't done e2e testing yet, so I don't know of a good way to make sure you wait until the .click() call finishes so you don't have a race condition between your expect()s and the whenClosed() logic, but I think you should be able to use the mock in the test like so:
it("opens a dialog when clicking on incomplete bank account", async done => {
// arrange
arrangeMemberVerificationStatus();
await component.create(bootstrap);
const vm = component.viewModel as GettingStartedCustomElement;
let mockDialogService = new MockDialogService();
vm.dialogService = mockDialogService; //Or however you're injecting the mock into the constructor; I don't see the code where you're doing that right now.
spyOn(mockDialogService, 'open').and.callThrough();
// act
$(".link, .-arrow")[0].click();
browser.sleep(100)//I'm guessing there's a better way to verify that it's finished with e2e testing, but the point is to make sure it finishes before we assert.
// assert
expect(mockDialogService.open).toHaveBeenCalledWith({ viewModel: AddAccountWizard });
expect(vm.steps[2].isCompleted).toBeTruthy(); // FAILS
done();
});

Angular2 unit testing a switchMap

Simple question:
I've followed the tutorial: here where I have the following code:
this.term.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => this.wikipediaService.search(term));
Where term is a Control inheriting from AbstractControl, how can I trigger the valueChanges observable property, so that I can perform unit tests?
I think I was experiencing the same issue.
I was trying to test that heroService.searchHeroes was called:
ngOnInit() {
this.heroes$ = this.searchTerms
.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((term: string) => this.heroService.searchHeroes(term))
);
}
I was able to fix it by only calling tick(500) once
it('should call HeroService.searchHeroes', fakeAsync(() => {
spyOn(heroService, 'searchHeroes').and.returnValue(component.heroes$);
let searchField: DebugElement = fixture.debugElement.query(By.css('#search-box'));
searchField.nativeElement.value = 'i';
searchField.nativeElement.dispatchEvent(new Event('keyup'));
tick(500);
expect(heroService.searchHeroes).toHaveBeenCalled();
}));
I found a work around in the following issue:
https://github.com/angular/angular/issues/8251
Essentially there's buggy behavior, but you can get a basic test working with code like this:
it("filter input changed should update filter string",
fakeAsync(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
let fixture = tcb.createFakeAsync(MyComponent);
let component = fixture.componentInstance as MyComponent;
fixture.detectChanges();
// Trigger a new value to emit on the valueChanges observable
//
component.filter.updateValue("testing");
// There's buggy behavior with multiple async events so we
// need to run tick() twice to get our desired behavior
// https://github.com/angular/angular/issues/8251
//
tick();
tick(500);
// Now we can inspect the results of the subscription in the
// original component
//
expect(component.filterString).toBe("testing");
})));
...and this is with a component that looks like this:
export class MyComponent {
filter = new Control();
/** The current filter string */
filterString: string;
constructor() {
// Subscribe to changes in the filter string
//
this.filter.valueChanges
.debounceTime(200)
.distinctUntilChanged()
.subscribe((filterString: string) => {
this.filterString = filterString;
});
}
}

How can i test a AngularJS provider?

I need to test my own angular provider, and I need to test it in both config and run phase to check that config methods work and that the instantiated provider is indeed configured with the correct parameters.
When I ask dependancy injection for the provider, it can't find the APIResourceFactoryProvider, only the APIResourceFactory, and I haven't found any examples of this on the repositories I've looked trough so far.
It's actually a lot simpler than it would at first seem to test a provider in AngularJS:
describe('Testing a provider', function() {
var provider;
beforeEach(module('plunker', function( myServiceProvider ) {
provider = myServiceProvider;
}));
it('should return true on method call', inject(function () {
expect( provider.method() ).toBeTruthy();
}));
});
```
The proof is in the Plunker: http://plnkr.co/edit/UkltiSG8sW7ICb9YBZSH
Just in case you'd like to have a minification-proof version of your provider, things become slightly more complicated.
Here is the provider code:
angular
.module('core.services')
.provider('storageService', [function () {
function isLocalStorageEnabled(window) {
return true;
}
this.$get = ['$window', 'chromeStorageService', 'html5StorageService',
function($window, chromeStorageService, html5StorageService) {
return isLocalStorageEnabled($window) ? html5StorageService : chromeStorageService;
}];
}]);
The test case:
describe('Storage.Provider', function() {
var chrome = {engine: 'chrome'};
var html5 = {engine: 'html5'};
var storageService, provider;
beforeEach(module('core.services'));
beforeEach(function () {
module(function (storageServiceProvider) {
provider = storageServiceProvider;
});
});
beforeEach(angular.mock.module(function($provide) {
$provide.value('html5StorageService', html5);
$provide.value('chromeStorageService', chrome);
}));
// the trick is here
beforeEach(inject(function($injector) {
storageService = $injector.invoke(provider.$get);
}));
it('should return Html5 storage service being run in a usual browser', function () {
expect(storageService).toBe(html5);
});
});
In this case $get is an array and you can't just call it as a usual function providing dependencies as arguments. The solution is to use $injector.invoke().
That's strange that most tutorials and samples miss this detail.
here is a little helper that properly encapsulates fetching providers, hence securing isolation between individual tests:
/**
* #description request a provider by name.
* IMPORTANT NOTE:
* 1) this function must be called before any calls to 'inject',
* because it itself calls 'module'.
* 2) the returned function must be called after any calls to 'module',
* because it itself calls 'inject'.
* #param {string} moduleName
* #param {string} providerName
* #returns {function} that returns the requested provider by calling 'inject'
* usage examples:
it('fetches a Provider in a "module" step and an "inject" step',
function() {
// 'module' step, no calls to 'inject' before this
var getProvider =
providerGetter('module.containing.provider', 'RequestedProvider');
// 'inject' step, no calls to 'module' after this
var requestedProvider = getProvider();
// done!
expect(requestedProvider.$get).toBeDefined();
});
*
it('also fetches a Provider in a single step', function() {
var requestedProvider =
providerGetter('module.containing.provider', 'RequestedProvider')();
expect(requestedProvider.$get).toBeDefined();
});
*/
function providerGetter(moduleName, providerName) {
var provider;
module(moduleName,
[providerName, function(Provider) { provider = Provider; }]);
return function() { inject(); return provider; }; // inject calls the above
}
the process of fetching the provider is fully encapsulated: no need for closure variables that compromise isolation between tests.
the process can be split in two steps, a 'module' step and an 'inject' step, which can be appropriately grouped with other calls to 'module' and 'inject' within a unit test.
if splitting is not required, retrieving a provider can simply be done in a single command!