jest Mocking a jQuery function from a promise - javascript

I have a function that calls a jQuery function.
the jQuery function called dataFunc and should return an object.
I want to test the promise, not the dataFunc function.
For that, I want to mock the response that dataFunc should return
I want this row const { data } = await service.auth( buttonData ); data to return
{ access_level: 0 };
How can I do that?
This is my code:
This function with the promise I want to test:
auth(buttonData){
const myPromise = new Promise((resolve, reject) => {
const success = (e, data) => {
resolve({data, error: null});
};
const error = () => {
resolve({data: null, error: 'Error'});
};
jQuery(buttonData).dataFunc({
success,
error,
});
});
return myPromise;
}
This is what I have done in jest so far:
describe('service.test.js', () => {
beforeEach(() => {
global.jQuery = () => {
return {
dataFunc: jest.fn(() => ({access_level: 0})),
};
};
});
afterEach(() => {
jest.clearAllMocks();
});
test('should do something', async () => {
// Arrange
const service = new Service();
const approveButton = document.createElement('button');
// Act
const {data} = await service.auth(buttonData);
console.log(data);
});
});

To fulfill auth function you need either reject or resolve the value.
However, when you mock jQuery method dataFunc to return an explicit value, you override the default behavior and it never calls resolve or reject. Therefore your promise will hang.
You don't necessarily need to mock but provide the original functionality dataFunc carries or provide one that is necessary for the current test.
To fix your example you can pass the argument and call it.
global.jQuery = () => {
return {
dataFunc: ({success, error}) => {
success(jest.fn(), {access_level: 0})
},
};
};

Related

Jest does not detect my mock call in promise .catch block

Jest does not seem to be detecting my mock calls in the catch block. Yet, if don't mock the method handleError, I'll receive an error. I have tried multiple ways of doing the returned rejected promise but no luck so far.
I've tried callbacks, Promise.reject, Promise((res, rej) => {})
Code being tested:
module.exports = class PresetDropdown {
constructor (Api, objectId, titleSort) {
this.Api = Api;
this.objectId; = objectId;
this.presets = [];
}
handleError (err) {
console.log(err)
// more functionality
}
get () {
this.Api.getMany(this.objectId)
.then((data) => {
this.handleEmpty(data);
this.isError = false;
})
.catch((err) => {
this.isError = true;
this.handleError(err);
});
}
};
Test (Jest):
test('Expect call from handleError after reject promise', async () => {
// assemble
// return the class
const Module = getModule();
const mockRejectedPromise = jest.fn(() => {
return Promise.reject(Error(mockError));
});
mockApi.getMany = mockRejectedPromise;
const module = new Module(mockApi, '1', null);
const mockHandleError = jest.fn(() => {});
PresetTemplate.handleError = mockHandleError;
// act
await PresetTemplate.get(mockScope);
// assert
expect(mockHandleError).toHaveBeenCalledTimes(1); // DOES NOT DETECT CALL
// Test CASE FAILS HERE ^
});
Since PresetDropdown class accept an Api object, you can create a mocked Api object and pass it to the class. Then mock resolved/rejected value for Api.getMany() method, so that you can test different code branches.
E.g.
presetDropdown.js:
module.exports = class PresetDropdown {
constructor(Api, objectId, titleSort) {
this.Api = Api;
this.objectId = objectId;
this.presets = [];
}
handleError(err) {
console.log(err);
}
handleEmpty(data) {
console.log(data);
}
get() {
return this.Api.getMany(this.objectId)
.then((data) => {
this.handleEmpty(data);
this.isError = false;
})
.catch((err) => {
this.isError = true;
this.handleError(err);
});
}
};
presetDropdown.test.js:
const PresetDropdown = require('./presetDropdown');
describe('71164955', () => {
test('should handle data', async () => {
const mockApi = {
getMany: jest.fn().mockResolvedValueOnce('fake data'),
};
const instance = new PresetDropdown(mockApi, '1');
await instance.get();
expect(instance.isError).toBeFalsy();
});
test('should handle error', async () => {
const mockError = new Error('fake error');
const mockApi = {
getMany: jest.fn().mockRejectedValueOnce(mockError),
};
const instance = new PresetDropdown(mockApi, '1');
await instance.get();
expect(instance.isError).toBeTruthy();
});
});
Test result:
PASS stackoverflow/71164955/presetDropdown.test.js
71164955
✓ should handle data (14 ms)
✓ should handle error (3 ms)
console.log
fake data
at PresetDropdown.handleEmpty (stackoverflow/71164955/presetDropdown.js:11:13)
console.log
Error: fake error
at Object.<anonymous> (/Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/stackoverflow/71164955/presetDropdown.test.js:12:23)
at Object.asyncJestTest (/Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:106:37)
at /Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/node_modules/jest-jasmine2/build/queueRunner.js:45:12
at new Promise (<anonymous>)
at mapper (/Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/node_modules/jest-jasmine2/build/queueRunner.js:28:19)
at /Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/node_modules/jest-jasmine2/build/queueRunner.js:75:41
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at PresetDropdown.handleError (stackoverflow/71164955/presetDropdown.js:8:13)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 1.311 s

Resolve promise after callback it's executed

I have the following code on which I am trying to block the execution of the method _saveAddress multiple time, so I made a promise for this method.
const [pressEventDisabled, setPressEventDisabled] = useState(false);
<TouchableOpacity style={style.button_container} activeOpacity={1} disabled={pressEventDisabled} onPress={async () => {setPressEventDisabled(true); await _saveAddress(); setPressEventDisabled(false);}} >
The problem is that I want to resolve the promise after the callback method it's executed. It's there any way to wait for the dispatch function to execute or to resolve the promise inside the callback method?
This is the method for saving the address:
const _saveAddress = () => new Promise(async (resolve) => {
var valid = _validate();
if (valid) {
const address = createAddressJson();
if (addressId) {
var addressIdProperty = {
id: addressId
};
const newAddress = Object.assign(addressIdProperty, address);
dispatch(editAddress(newAddress, _onAddressSaveEditCallback));
} else {
dispatch(addAddress(address, _onAddressSaveEditCallback));
}
} else {
//notify
notifyMessage(strings.fill_required_inputs_validation);
resolve();
}
});
This is the callback method:
const _onAddressSaveEditCallback = async (success: boolean, apiValidations: any, address ? : Address, ) => {
if (success) {
if (typeof callback == 'function') {
callback(address);
}
await Navigation.pop(componentId);
} else {
setDataValidations(apiValidations);
}
};
Just do exactly what you say in the title. Nothing more, nothing less:
if (addressId) {
var addressIdProperty = {id: addressId};
const newAddress = Object.assign(addressIdProperty, address);
dispatch(editAddress(newAddress, async (s,v,a) => {
await _onAddressSaveEditCallback(s,v,a);
resolve();
}));
} else {
dispatch(addAddress(address, async (s,v,a) => {
await _onAddressSaveEditCallback(s,v,a);
resolve();
}));
}
Of course, since you are passing async () => {} to addAddress instead of _onAddressSaveEditCallback you have to call _onAddressSaveEditCallback yourself since addAddress will be calling the async () => ...
But mixing promises and callbacks like this isn't great. It leads to weird looking and sometimes confusing code. A better solution is to promisify addAddress:
function addAddressPromise (address) {
return new Promise((resolve, reject) => {
addAddress(address, (success, validations, address) {
if (success) return resolve(address);
else reject(validations)
});
});
}
Now you can wait for addAddress:
const _saveAddress = async () => {
// Don't create new promise here, we do it in addAddress..
// ...
let result = await addAddressPromise(address);
dispatch(result);
await _onAddressSaveEditCallback();
// ...
}

is there a function to test an object instance that has a callback in js?

Im using sinon to stub an instance of an object that has inside a function with a callback, how can i test it?.
i dont know how to test this, that throws me an error.
this is using js with sinon and mocha.
the function is:
import tracker from 'pivotaltracker';
export async function getPivotalProjects(token) {
const clientTracker = new tracker.Client(token);
const userProjects = () => new Promise((resolve, reject) => {
clientTracker.projects.all((error, projects) => (projects ? resolve(projects) : reject(error)));
});
return userProjects();
and the test is:
import tracker from 'pivotaltracker';
let spyTracker;
beforeEach(() => {
spyTracker = sinon.stub(tracker, 'Client');
});
it('should do the request to get the activities from projects.', async () => {
spyTracker.callsArgWith(1, null, [true, 'token']);
// spyTracker.projects.all.returns('token');
await PivotalTrackerApi.getPivotalProjects('token');
sinon.assert.threw(spyTracker);
spyTracker.restore();
});
what is wrong on that? if anyone could helpme will be great.
getPivotalProjects can be simplified to this:
export async function getPivotalProjects(token) {
const clientTracker = new tracker.Client(token);
await new Promise((resolve, reject) => {
clientTracker.projects.all((error, projects) => (projects ? resolve(projects) : reject(error)));
});
}
...and it can be tested like this:
let clientStub;
beforeEach(() => {
clientStub = sinon.stub(tracker, 'Client');
});
it('should do the request to get the activities from projects.', async () => {
const allSpy = sinon.spy();
clientStub.callsFake((token) => ({ projects: { all: allSpy } }));
const promise = PivotalTrackerApi.getPivotalProjects('token');
sinon.assert.calledWith(clientStub, 'token'); // Success!
sinon.assert.called(allSpy); // Success!
const callback = allSpy.lastCall.args[0];
callback(null, 'my projects');
const result = await promise;
expect(result).to.equal('my projects'); // Success!
});

Testing Redux Thunk Action Creator

I've got a redux action creator that utilizes redux-thunk to do some logic to determine what to dispatch to the store. Its not promise-based, like an HTTP request would be, so I am having some issues with how to test it properly. Ill need a test for when the value meets the condition and for when it doesn't. Since the action creator does not return a promise, I cannot run a .then() in my test. What is the best way to test something like this?
Likewise, I believe it would be pretty straightforward testing the getRemoveFileMetrics() action creator as it actually does return a promise. But how can I assert that that will called if the value is removeFiles and meets the condition? How can that be written in the test?
Thanks in advance as this has had me stuck for the last couple of days.
Action Creators
export const handleSelection = (value, cacheKey) => {
return dispatch => {
if (value === "removeFiles") {
dispatch(getRemoveFileMetrics(cacheKey));
}
dispatch({ type: HANDLE_SELECTION, value });
};
};
export const getRemoveFileMetrics = cacheKey => {
return dispatch => {
dispatch({ type: IS_FETCHING_DELETE_METRICS });
return axios
.get(`../GetRemoveFileMetrics`, { params: { cacheKey } })
.then(response => {
dispatch({ type: GET_REMOVE_FILE_METRICS, payload: response.data });
})
.catch(err => console.log(err));
};
};
Jest
it("should dispatch HANDLE_SELECTION when selecting operation", () => {
const store = mockStore({});
const value = "switchVersion";
const expectedAction = [{
type: MOA.HANDLE_SELECTION,
value,
}]; // TypeError: Cannot read property 'then' of undefined
return store.dispatch(MOA.handleSelection(value)).then(() => {
const returnedActions = store.getActions();
expect(returnedActions).toEqual(expectedAction);
});
});
NEW EDIT
So based off of Danny Delott's answer to return a promise, I acheived a passing test as follows:
export const handleSelection = (value, cacheKey) => {
return dispatch => {
if (value === "removeFiles") {
return dispatch(getRemoveFileMetrics(cacheKey));
}
return new Promise((resolve, reject) => {
resolve(dispatch({ type: HANDLE_SELECTION, value }));
});
};
};
Is there a reason to explicitly NOT return a promise in your action creator? It looks like getRemoveFileMetrics is returning the promise, it just gets swallowed in handleSelection...
Easiest solution is to just return the promise:
export const handleSelection = (value, cacheKey) => {
return dispatch => {
if (value === "removeFiles") {
return dispatch(getRemoveFileMetrics(cacheKey));
}
dispatch({ type: HANDLE_SELECTION, value });
return new Promise();
};
};
Otherwise, you'll need make your assertions after the event loop is finished. You can do with a setTimeout wrapped in a Promise to get the .then behavior.
it("should dispatch HANDLE_SELECTION when selecting operation", () => {
const store = mockStore({});
const value = "switchVersion";
const expectedAction = [{
type: MOA.HANDLE_SELECTION,
value,
}];
store.dispatch(MOA.handleSelection(value));
// flush outstanding async tasks
return new Promise(resolve => {
setTimeout(resolve, 0);
})
.then(() => {
const returnedActions = store.getActions();
expect(returnedActions).toEqual(expectedAction);
});
});

How to return value from callback in Graphql resolve function?

How do I return the value from callback function and pass it to resolve function in Graphql?
Here's the dummy code to show the concept:
This function runs the sql query:
function runQuery(query, cb){
....
var value = "Something";
cb(null, value);
}
This takes the value from callback function pass it to resolve function in graphql:
function getTitle() {
return runQuery("...", function(err, value){
return value;
});
}
Graphql schema:
var SampleType = new GraphQLObjectType({
name: 'Sample',
fields: () => ({
title: { type: GraphQLString },
}),
});
query: new GraphQLObjectType({
name: 'Query',
fields: () => ({
sample: {
type: SampleType,
resolve: () => getTitle(),
},
}),
}),
You can make use of promises and async to accomplish this.
async function getTitle() {
const queryResult = await runQuery("...");
// ...
// Do post-query stuff here that you currently have in your callback
// ...
return queryResult
}
async function runQuery() {
const value = 'something';
// ...
return value;
}
Node fully supports async/await as of 7.10.0. Use TypeScript or Babel if you're in the browser or are locked into a lower version of node.
Basically you can create a promise around that runQuery so that you can use async await when using the query data
const getTitle = () => {
return new Promise((resolve, reject) => {
runQuery("...", (error, response) => !error
? resolve(response)
: reject(error))
})
}
const asyncFunction = async () => {
const data = await getTitle()
.then((response) => {
// handle response and return what you want
return response.data
})
.catch((error) => {
// handle error, log it, etc, in whatever way you want
console.log(error.message)
return null
})
if(data) { // data is valid
// do what you want with the valid data (no error)
} else { // there was an error
// handle if there is an error
}
}
asyncFunction()

Categories

Resources