How to test a function composition with side effects without using mocks? - javascript

I have a function, MyComposedFunction, which is the function composition of 3 functions the second function, fn2, performs a POST request (a side effect) using the result of fn1 and passes this value to fn3.
const fn2 = async (fn1Result) => {
const result = await fetch(fn1Result.url, fn1Result.payload);
// some business logic
return fn2Results;
};
const MyComposedFunction = compose(fn3, fn2, fn1);
// My Test
expect(MyComposedFunction('hello world')).toBe('expected result');
I'd like to avoid writing unit tests for fn3, fn2, and fn1 and instead only test MyComposedFunction. My rationale is that it should not matter whether MyComposedFunction uses compose(...) or is one long giant function as long as MyComposedFunction works.
Is it possible to write a test for MyComposedFunction without having to mock fn2?
I would think that this must be a relatively common situation when trying to do functional programming in JavaScript but haven't been able to find a helpful resource so far.

You can dependency inject fetch into your function like so
const fn2Thunk = (fetcher = fetch) => async (fn1Result) => {
const result = await fetcher(fn1Result.url, fn1Result.payload);
// some business logic
return fn2Results;
};
const fetchMock = async () => ({ result: "blah" })
const MyComposedFunctionTest = compose(fn3, fn2Thunk(fetchMock), fn1);
// My Test
const result = await MyComposedFunctionTest('hello world')
expect(result).toBe('expected result');

Related

Jasmine - How to spy on a deep nested function

I have the following scenario:
file1.js:
async function fctionA(event) {
console.log('In fctionA()!');
let responseA = null;
const formattedEvent = formatEvent(event);
...
const b = await fctionB(formattedEvent);
responseA = someLogicUsing(b);
return responseA; // responseA will depend on 'b'
}
file2.js:
async function fctionB(formattedEvent) {
console.log('Now in fctionB()!');
let resB = null;
...
const c = await fctionC(formattedEvent);
...
resB = someLogicDependingOn(c); // resB will depend on 'c'
return resB;
}
async function fctionC(formattedEvent) {
console.log('AND now in fctionC()!');
let c = await someHttpRequest(formattedEvent);
...
return c;
}
Side notes:
Don't mind formatEvent(), someLogicUsing() orsomeLogicDependingOn() too much. Assume it's just sync logic using provided data)
formattedEvent would be anything depending on the original input event. Just to note functions will use it.
PROBLEM:
What i want to do is to unit test fctionA(), using Jasmine: I want to check the responseA after appying the logic on fctionB(), but mock the result of fctionC().
My (clearly) naive approach was:
file1.spec.js
import * as Handler from '../src/file1';
import * as utils from '..src//file2';
describe('fctionA', () => {
let response = null;
beforeAll(async () => {
const mockedEventA = { mockedInput: 'a' };
const mockedC = { mockedData: 1 };
const expectedResponse = { mockedResponse: 1234 };
spyOn(utils, 'fctionB').and.callThrough());
spyOn(utils, 'fctionC').and.returnValue(Promise.resolve(mockedC));
response = await Handler.fctionA(mockedEventA);
});
it('should return a proper response', () = {
expect(response).toEqual(expectedResponse);
});
});
But after checking logs, i can see that ´fctionC()´ does get executed (when as far as i understood, it shouldn't), therefore does not return the mocked result.
Then, after some try and error, i invoked fctionC() directly in fctionA() (instead of indirectly invoking it through´fctionB()´) just to see what happens, and I can spy it and return a mocked value. fctionC() does not execute (can't see log).
So, that makes me think that, at least the way I'm trying to spy on functions, only work for functions that are directly invoked by the function I'm calling, but not for nested ones-
I'm clearly not an expert in Jasmine, so I can't figure out another option. I looked a lot into docs and posts and blogs but nothing worked for me.
Is there a way to achieve what I try here? I guess I might be doing something really silly or not thinking it through.
Thanks!

How to control flow of async functions?

I have a chain of async functions, which need to be performed in order. Yet, if one of those functions fails or takes too long, it should be retriggered a certain amount of times.
So my questions is:
What is the standard/elegant structure to have such a control flow with async functions? E.g.:
funcA()
.then(resultA => funcB(resultA)
.then(resultB => funcC(resultB)
.then(...))
You can do like this
function funcA() {
return Promise.resolve('a');
}
function funcB(data) {
return Promise.resolve(data + ' b');
}
function funcC(data) {
return Promise.resolve(data + ' c');
}
async function controlFlowExample() {
const resultA = await funcA();
const resultB = await funcB(resultA);
const resultC = await funcC(resultB);
console.log(resultC);
}
controlFlowExample();
You can use async-await to chain them neatly together:
const res_a = await funcA()
const res_b = await funcB(res_a)
const res_c = await funcC(res_b)
This is better than chaining .then since here it is easier to debug as you save more values.
Sidenote: if you do it this way, it is best to implement trycatch within your functions.
IMO it looks much neater too.

Sequential async function explanation

This is a test case from one company. I need to translate this function into Typescript and explain how to test it. But I even don't understand what is going on here. I understand every part of that code, but a whole picture still doesn't clear for me. Could someone explain how that piece of code works step by step?
I think I need some simple analog for this. Maybe some metaphor. Also, I'm not sure how to test that to see how this function should work.
// Makes your async function sequential. It means that next call won't be performed until the previous one finishes.
// This function is a wrapper for async functions
export function sequentialize(func: (...args: any[]) => any) {
// we create an immideately resolved promise
// we can use that because of closure mechanism
let previousCall: Promise<any> = Promise.resolve();
// return wrapper that will call original function with args
return function (...args: any[]): Promise<any> {
// Here I'm a bit confused. I know that with then we set a callback that
// will work after promise will be fullfiled. But why we save this in variable
const currentCall: Promise<any> = previousCall.then(() =>
// call original wrapped async function with args
func.apply(this, args)
);
console.log(currentCall);
// this part is not clear for me too
previousCall = currentCall.catch(() => {});
return currentCall;
};
}
// I use this code to test
const url = "https://jsonplaceholder.typicode.com/todos/1";
const myAsyncFunction = (url) => {
return fetch(url)
.then((response) => response.json())
.then((json) => console.log(json));
};
const sequentializeFunc = sequentialize(myAsyncFunction);
sequentializeFunc(url);
UPDATE: add ts and some comments to parts I already understand.

How to get rid of async in function?

Let's say I have this code:
const myFunction = async => {
const result = await foobar()
}
const foobar = async () => {
const result = {}
result.foo = await foo()
result.bar = await bar()
return result
}
And I want this:
const myFunction = () => {
const result = foobar()
}
I tried to wrap foobar like this:
const foobar = async () => {
return (async () => {
const result = {}
result.foo = await foo()
result.bar = await bar()
return result
})()
}
But this still return a promise
I can't use .then in myFunction, I need that foobar returns the result variable instead a promise.
The problem is that myFunction is an async function and it will return a promise but It should return undefine I need to get rid of async in myFunction.
Edit: as Sebastian Speitel said, I want to convert myFunction to sync
Edit 2: to Shilly, I am using nightwatch for end2end test, nightwatch will call myFunction() if there are no errors in the execution of the function it will run perfectly, if there's an error then nightwatch's virtual machines will run forever instead stop, this problem happens if the called function is async.
To change an asynchronous function into a normal synchronous function you simply have to drop the async keyword and as a result all await keywords within that function.
const myFunction = async () => {
const result = await foobar();
// ...
return 'value';
};
// becomes
const myFunction = () => {
const result = foobar();
// ...
return 'value';
};
You should however keep one simple rule in mind.
You can't change a asynchronous function into a synchronous function if the return value depends on the value(s) of the resolved promise(s).
This means that functions that handle promises inside their body, but from whom the return value doesn't depend on those resolved promises are perfectly fine as synchronous functions. In most other scenarios you can't drop the asynchronous behaviour.
The following code gives you an example for your situation, assuming the return value of myFunction doesn't depend on the resolved promise.
const myFunction = () => {
const result = foobar();
result.then(data => doSomethingElse(data))
.catch(error => console.error(error));
return 'some value not dependent on the promise result';
};
If you want to learn more about promises I suggest checking out the promises guide and the async/await page.
Have you looked into using .executeAsync() and then having the promise call the .done() callback? That way it should be possible to wrap foobar and just keep either the async or any .then() calls inside that wrapper.
My nightwatch knowledge is very stale, but maybe something like:
() => {
client.executeAsync(( data, done ) => {
const result = await foobar();
done( result );
});
};
or:
() => {
client.executeAsync(( data, done ) => foobar().then( result => done( result )));
};
Any function marked with async will return a Promise. This:
const foobar = async () => {
return 7;
}
Will a return a Promise of 7. This is completely independent of wether the function that calls foobar is async or not, or uses await or not when calling it.
So, you're problem is not (only) with myFunction: is foobar using async which forces it to always return a Promise.
Now, said that, you probably can't achieve what you want. Async-Await is only syntax sugar for promises. What you're trying is to return a synchronous value from an asynchronous operation, and this is basically forbidden in javascript.
You're missing very important understanding here between the synchronous and asynchronous nature of the code.
Not every async function can be converted to synchronous function. You can use callback pattern instead of await/async, but I doubt that would be useful to you.
Instead I would recommend you just use await, as in your first code example, and leave functions as async, it shouldn't harm your logic.
Check this out
function foo(){
return 'foo'
}
function bar(){
return 'bar'
}
const foobar = () => {
return new Promise((resolve)=>{
let result = {}
result.foo = foo()
result.bar = bar()
return resolve(result)
})
}
const myFunction = () => {
const result = foobar()
let response = {}
result.then(val=>{
response = Object.assign({}, val);
return response
});
}
var test = myFunction()
console.log(test)

Can I force the resolution of a promise to await results in javascript?

This question is somewhat academic in that I don't have a real need to do this.
I'm wondering if I can force the resolution of a promise into a returned value from a function such that the function callers are not aware that the functions contain promised async operations.
In .NET I can do things like this by using functions on Task[] or return Task.Result which causes the caller to await the completion of the task and callers won't know or care that the work has been done using tasks.
If you're using ES6 you can use a generator to make code like this. It essentially comes close to 'blocking' on the promise, so you have the appearance of a long-running method that just returns the value you want, but async/promises live under the covers.
let asyncTask = () =>
new Promise(resolve => {
let delay = Math.floor(Math.random() * 100);
setTimeout(function () {
resolve(delay);
}, delay);
});
let makeMeLookSync = fn => {
let iterator = fn();
let loop = result => {
!result.done && result.value.then(res =>
loop(iterator.next(res)));
};
loop(iterator.next());
};
makeMeLookSync(function* () {
let result = yield asyncTask();
console.log(result);
});
More explanation and the source available here: http://www.tivix.com/blog/making-promises-in-a-synchronous-manner/
Here is the code compiled on Babeljs.io

Categories

Resources