How to unit test nested subscribe methods in Angular? - javascript

MethodToBeTested() {
this.serviceA.methodA1().subscribe((response) => {
if (response.Success) {
this.serviceA.methodA2().subscribe((res) => {
this.serviceB.methodB1();
})
}
});
}
Here is the scenario.
Things to test:
serviceA.methodA1(). was called.
if response.Success then check if serviceA.methodA2() was called
check if serviceB.methodB1() was called when serviceA.methodA2() received value.
first, one is easy to test.
let spy = spyOn(serviceA, 'methodA1');
expect(spy).toHaveBeenCalled();
But does one test 2 and 3?
let spy= spyOn(serviceA, 'methodA1').and.returnValue({subscribe: () => {success:true}});
subject.MethodToBeTested();
something like that?

Alright, so I figured out what I am looking for is callFake
it('should test inside of subscribe', () => {
let spy = spyOn(serviceA, 'methodA1').and.callFake(() => {
return of({ success: true });
});
let spy2 = spyOn(serviceA, 'methodA2').and.callFake(() => {
return of({ success: true });
});
let spy3 = spyOn(serviceB, 'methodB1').and.returnValue(of({ success: true }));
subject.MethodToBeTested();
expect(spy3).toHaveBeenCalled();
});
I learned that returnValue won't actually execute the inside of the subscribe while callFake will with the data you provide inside it.

It would be better to not use a nested subscribe.
Something like this could be a sollution:
let $obs1 = this.serviceA.methodA1().pipe(share());
let $obs2 = $obs1.pipe(switchMap(x => this.serviceA.methodA2()));
$obs1.subsribe(logic1 here...);
$obs2.subsribe(logic2 here...);

Related

How to invoke function by reference

I rendered a list of modal/popups and control them by using state.
renderGenericOKModal({ title, message, visibleStateVar }) {
return (
<PromptModal
alertTitle={title}
alertMessage={message}
isVisible={this.state[visibleStateVar]}
onRightButtonPress={() =>
this.setState({ [visibleStateVar]: false });
}
rightButtonLabel={strings.labelOK}
/>
);
}
I see some comments on medium saying that the code above is not optimized because it creates a lot of unnecessarily similar function for onRightButtonPress. So I tried to do something as below but not sure if it actually make any differences?
genericOKButtonOnPress = ({ visibleStateVar }) => {
this.setState({ [visibleStateVar]: false });
};
onRightButtonPress={() =>
this.genericOKButtonOnPress({ visibleStateVar })
}
But the code above is still creating each individual anonymous function object which looks the same as my original code right?
UPDATES:
onRightButtonPress={this.genericOKButtonOnPress.bind(null, {
visibleStateVar
})}
Using bind should be beneficial for my case right?
Define the onRightButtonPress using arrow function without anonymous function.
onRightButtonPress = () => this.genericOKButtonOnPress({ visibleStateVar }) //inline
or
onRightButtonPress = () => {
this.genericOKButtonOnPress({ visibleStateVar })
} //using block
PromptModal should be
<PromptModal
alertTitle={title}
alertMessage={message}
isVisible={this.state[visibleStateVar]}
onRightButtonPress=this.onRightButtonPress
rightButtonLabel={strings.labelOK}
/>

Testing function within same file is called

I have 2 functions where one calls the other and the other returns something, but I cannot get the test to work.
Using expect(x).toHaveBeenCalledWith(someParams); expects a spy to be used, but I am unaware of how to spy on a function within the same file...
Error: : Expected a spy, but got Function.
Usage: expect().toHaveBeenCalledWith(...arguments)
Example.ts
doSomething(word: string) {
if (word === 'hello') {
return this.somethingElse(1);
}
return;
}
somethingElse(num: number) {
var x = { "num": num };
return x;
}
Example.spec.ts
fake = {"num": "1"};
it('should call somethingElse', () => {
component.doSomething('hello');
expect(component.somethingElse).toHaveBeenCalledWith(1);
});
it('should return object', () => {
expect(component.somethingElse(1)).toEqual(fake);
});
In your Example.spec.ts, just add a spyOn(component, 'somethingElse'); as first line of your it('should call somethingElse ... test :
fake = {"num": "1"};
it('should call somethingElse', () => {
// Add the line below.
spyOn(component, 'somethingElse');
component.doSomething('hello');
expect(component.somethingElse).toHaveBeenCalledWith(1);
});
it('should return object', () => {
expect(component.somethingElse(1)).toEqual(fake);
});
The expect method needs a Spy as parameter when used before a toHaveBeenCalledWith (as per the Jasmine documentation).

react component this.value is null even when it's populated

Here a simplified version of a React component I have:
class Example extends Component {
constructor(props) {
super(props);
this.state = {key : 10 };
this.value = null;
}
componentDidMount() {
this.fetchValueFromServer();
this.fetchSecondValueFromServer();
}
fetchValueFromServer() {
fetch_value_from_server(this.state.key).then( (value) => {
this.value = value;
});
}
fetchSecondValueFromServer() {
is_ready(this.value).then(() => {
console.log("there");
});
}
}
I expect to see the console.log("there") printed but this.value always remains null, even thou is set in the fetchValueFromServer. Why is this?
if you are curious to how is_ready looks it's a simple promise:
function is_ready(variable) {
return new Promise((resolve, reject) => {
let interval = setInterval(() =>
{
if (variable) {
clearInterval(interval);
resolve();
}
}, 100);
});
}
The problem is with the logic of the is_ready function. It looks like you want that function to repeatedly check if that value is there, then resolve when it is. However, because of how closures in JS work, that variable argument will only ever have one value in the context of that function's body, even after this.value changes. Look at this small example:
let secret = 'not found yet'
function checkSecret(secretArg) {
setInterval(() => {
console.log(secretArg)
}, 500)
}
checkSecret(secret)
setTimeout(() => { secret = 'secret found!' }, 1000)
This code will always print 'not found yet', because it's checking the secretArg variable that's been assigned locally, and not the secret variable directly.
Looks like you need to resolve with the variable value within the function is_ready, like so:
resolve(variable);
Then add a param to your console log to determine more, like so:
fetchSecondValueFromServer() {
is_ready(this.value).then((returnValue) => {
console.log("there", returnValue);
});
}
figured it, the value in is_ready is passed by value! Javascript needs to implement & so we can pass crap by ref!

Passing arguments while running lodash flow asynchronously

Given the code below, how can I pass id to the applySaveAsync function?
var then = _.curry(function (f, thenable) {
return thenable.then(f);
});
var validateAsync = _.flow(
function () { return _(someCondition).showError(ERROR_01).value(); },
then(function () { return _(anotherCondition).showError(ERROR_02).value(); })
);
var save = _.flow(
validateAsync,
then(applySaveAsync),
then(saveCompleted)
);
function applySaveAsync(id) {
// Saving...
}
save(22); // Calling save function with some id.
I can get the id on the validateAsync function, but I cannot return it back since validateAsync should return a promise.
Any way to achieve that?
The simplest choice would be not to use _.flow for the definition of validateAsync.
Since validateAsync does not take parameters nor has a result, you should just change the definition of save to not use _.flow:
function save(id) {
return validateAsync()
.then(function(){ return applySaveAsync(id) })
.then(saveCompleted)
}
We could also change validateAsync to pass through the id:
function validateAsync(id) {
return _(someCondition).showError(ERROR_01).value()
.then(function () { return _(anotherCondition).showError(ERROR_02).value(); })
.then(_.constant(id));
}
and even do that while still using _.flow
var validateAsync = _.flow(
function(id) { return _(someCondition).showError(ERROR_01).value().then(_.constant(id)); },
then(function(id) { return _(anotherCondition).showError(ERROR_02).value().then(_.constant(id)); })
);
but I would advise against that since validateAsync is not supposed to be a function that does takes parameters.
Let's write a wrapper function for such instead to let us do the pass-around in a functional way:
function pass(fn) {
return function(id) {
return fn().then(function() {
return id;
});
}
}
(if you prefer, you can try to compose that from then, _.constant and more)
so that one can write
var save = _.flow(
wrap(validateAsync),
then(applySaveAsync),
then(saveCompleted)
);
I found this package useful for you. In Async cases, you can use this package.
Although flow is one of the best implementations for declarative programming, it doesn't support modern JS programming style.
import { Conductor } from '#puzzleio/conductor';
const conductor = Conductor.createDefault();
const myAsyncWorkflow = conductor
.add(validateAsync)
.if({
check: item => item.isValid === true,
handler: item => console.log('Item is valid')
},
{
// else block
handler: item => console.log('Validation failed')
});
myAsyncWorkflow.run(obj)
.then(() => console.log('Successfully validated'))
.catch(console.error);

Unsubscribe from Redux store when condition is true?

I'm employing the suggestion from #gaearon to setup a listener on my redux store. I'm using this format:
function observeStore(store, select, onChange) {
let currentState;
if (!Function.prototype.isPrototypeOf(select)) {
select = (state) => state;
}
function handleChange() {
let nextState = select(store.getState());
if (nextState !== currentState) {
currentState = nextState;
onChange(currentState);
}
}
let unsubscribe = store.subscribe(handleChange);
handleChange();
return unsubscribe;
}
I'm using this in an onEnter handler for a react-router route:
Entity.onEnter = function makeFetchEntity(store) {
return function fetchEntity(nextState, replace, callback) {
const disposeRouteHandler = observeStore(store, null, (state) => {
const conditions = [
isLoaded(state.thing1),
isLoaded(state.thing2),
isLoaded(state.thing3),
];
if (conditions.every((test) => !!test) {
callback(); // allow react-router to complete routing
// I'm done: how do I dispose the store subscription???
}
});
store.dispatch(
entities.getOrCreate({
entitiesState: store.getState().entities,
nextState,
})
);
};
};
Basically this helps gate the progression of the router while actions are finishing dispatching (async).
My problem is that I can't figure out where to call disposeRouteHandler(). If I call it right after the definition, my onChange function never gets a chance to do it's thing, and I can't put it inside the onChange function because it's not defined yet.
Appears to me to be a chicken-egg problem. Would really appreciate any help/guidance/insight.
How about:
Entity.onEnter = function makeFetchEntity(store) {
return function fetchEntity(nextState, replace, callback) {
let shouldDispose = false;
const disposeRouteHandler = observeStore(store, null, (state) => {
const conditions = [
isLoaded(state.thing1),
isLoaded(state.thing2),
isLoaded(state.thing3),
];
if (conditions.every((test) => !!test) {
callback(); // allow react-router to complete routing
if (disposeRouteHandler) {
disposeRouteHandler();
} else {
shouldDispose = true;
}
}
});
if (shouldDispose) {
disposeRouteHandler();
}
store.dispatch(
entities.getOrCreate({
entitiesState: store.getState().entities,
nextState,
})
);
};
};
Even though using the observable pattern leads to some buy-in, you can work around any difficulties with normal js code. Alternatively you can modify your observable to suit your needs better.
For instance:
function observeStore(store, select, onChange) {
let currentState, unsubscribe;
if (!Function.prototype.isPrototypeOf(select)) {
select = (state) => state;
}
function handleChange() {
let nextState = select(store.getState());
if (nextState !== currentState) {
currentState = nextState;
onChange(currentState, unsubscribe);
}
}
unsubscribe = store.subscribe(handleChange);
handleChange();
return unsubscribe;
}
and
Entity.onEnter = function makeFetchEntity(store) {
return function fetchEntity(nextState, replace, callback) {
const disposeRouteHandler = observeStore(store, null, (state, disposeRouteHandler) => {
const conditions = [
isLoaded(state.thing1),
isLoaded(state.thing2),
isLoaded(state.thing3),
];
if (conditions.every((test) => !!test) {
callback(); // allow react-router to complete routing
disposeRouteHandler();
}
}
store.dispatch(
entities.getOrCreate({
entitiesState: store.getState().entities,
nextState,
})
);
};
};
It does add a strange argument to onChange but it's just one of many ways to do it.
The core problem is that handleChange gets called synchronously immediately when nothing has changed yet and asynchronously later. It's known as Zalgo.
Inspired by the suggestion from #DDS, I came up with the following alteration to the other pattern mentioned in #gaearon's comment:
export function toObservable(store) {
return {
subscribe({ onNext }) {
let dispose = this.dispose = store.subscribe(() => {
onNext.bind(this)(store.getState())
});
onNext.bind(this)(store.getState());
return { dispose };
},
dispose: function() {},
}
}
This allows me to invoke like:
Entity.onEnter = function makeFetchEntity(store) {
return function fetchEntity(nextState, replace, callback) {
toObservable(store).subscribe({
onNext: function onNext(state) {
const conditions = [/* many conditions */];
if (conditions.every((test) => !!test) {
callback(); // allow react-router to complete routing
this.dispose(); // remove the store subscription
}
},
});
store.dispatch(/* action */);
};
};
The key difference is that I'm passing a regular function in for onNext so as not to interfere with my bind(this) in toObservable; I couldn't figure out how to force the binding to use the context I wanted.
This solution avoids
add[ing] a strange argument to onChange
... and in my opinion also conveys a bit more intent: this.dispose() is called from within onNext, so it kinda reads like onNext.dispose(), which is exactly what I want to do.

Categories