How to use Promise's reject? - ionic2

As the documentation says
resolve is
The Promise.resolve(value) method returns a Promise object that is
resolved with the given value.
reject is
The Promise.reject(reason) method returns a Promise object that is
rejected with the given reason.
I understand the uses of resolve but what will be the uses of reject and when to use it ?

Promise.reject is promise's way of throwing errors. Usually you would have a condition inside of your promise:
const user = {
name: 'John',
age: 17
}
const p = new Promise((resolve, reject) => {
if (user.age > 18) {
resolve('Welcome!');
} else {
reject(new Error('Too young!'));
}
});
You can then chain then and catch methods to handle the results of resolve and reject respectively.
p.then(message => {
console.log(message); // 'Welcome!', if promise resolves, won't work with age of 17
})
.catch(err => {
console.error(err); // 'Too young!', because promise was rejected
});

Here are few examples this statement can be used for:
Function defined to return a Promise, however you perform some sync checks and would like to return an error:
function request(data) {
if (!data) return Promise.reject("Empty data!");
// other logic
}
Unit tests, for example you would like to test that default data is used if service returns error (rejected promise):
const mockService = mock(Service);
// mock request method to return rejected promise
when(mockService.performRequest()).thenReturn(Promise.reject("Failed!"));
// inject mock instance and check that default data used if service failed
const sut = new ClassUnderTest(mockService);
expect(sut.getData()).to.eq("Default data");

Related

jest.spyOn mock return value not returning value

The code I'm trying to test:
const utils = require('../utils/utils');
let imageBuffer;
try {
imageBuffer = await utils.retrieveImageFromURI(params)
console.log(imageBuffer) // comes back as undefined when I mock the utils.retreieveImageFromURI
if (!imageBuffer || imageBuffer.length < 1024) {
throw new Error(`Retrieve from uri (${params.camera.ingest.uri}) was less than 1kb in size - indicating an error`)
}
console.log(`${params.camera.camId} - Successful Ingestion from URI`);
} catch (err) {
reject({ 'Task': `Attempting to pull image from camera (${params.camera.camId}) at ${params.camera.ingest.uri}`, 'Error': err.message, 'Stack': err.stack })
return;
}
Specifically, I'm trying to mock the utils.retrieveImageFromURI function - which has API calls and other things in it.
When I try to mock the function using spyOn I am trying it like so:
describe("FUNCTION: ingestAndSave", () => {
let fakeImageBuffer = Array(1200).fill('a').join('b'); // just get a long string
console.log(fakeImageBuffer.length) //2399
let retrieveImageFromURISpy
beforeAll(() => {
retrieveImageFromURISpy = jest.spyOn(utils, 'retrieveImageFromURI').mockReturnValue(fakeImageBuffer)
})
test("Will call retrieveImageFromURI", async () => {
await ingest.ingestAndSave({camera:TEST_CONSTANTS.validCameraObject, sourceQueueURL:"httpexamplecom", receiptHandle: "1234abcd"})
expect(retrieveImageFromURISpy).toHaveBeenCalledTimes(1)
})
afterEach(() => {
jest.resetAllMocks()
})
afterAll(() => {
jest.restoreAllMocks()
})
})
When I do this, I get a console log that imageBuffer (which is supposed to be the return of the mocked function) is undefined and that, in turn, triggers the thrown Error that "Retrieve from uri ...." ... which causes my test to fail. I know I could wrap the test call in a try/catch but the very next test will be a "does not throw error" test... so this needs to be solved.
It's not clear to me why the mockReturnValue isn't getting returned.
Other steps:
I've gone to the REAL retrieveImageFromURI function and added a console log - it is not running.
I've changed mockReturnValue to mockImplementation like so:
retrieveImageFromURISpy = jest.spyOn(utils, 'retrieveImageFromURI').mockImplementation(() => {
console.log("Here")
return fakeImageBuffer
})
And it does NOT console log 'here'. I'm unsure why not.
I have also tried to return it as a resolved Promise, like so:
retrieveImageFromURISpy = jest.spyOn(utils, 'retrieveImageFromURI').mockImplementation(() => {
console.log("Here")
return Promise.resolve(fakeImageBuffer)
})
Note, this also doesn't console log.
I've also tried to return the promise directly with a mockReturnValue:
`retrieveImageFromURISpy = jest.spyOn(utils, 'retrieveImageFromURI').mockReturnValue(Promise.resolve(fakeImageBuffer)`)

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 return error response in apollo link?

I'm using apollo link in schema stitching as an access control layer. I'm not quite sure how to make the link return error response if a user does not have permissions to access a particular operation. I know about such packages as graphql-shield and graphql-middleware but I'm curious whether it's possible to achieve basic access control using apollo link.
Here's what my link looks like:
const link = setContext((request, previousContext) => merge({
headers: {
...headers,
context: `${JSON.stringify(previousContext.graphqlContext ? _.omit(previousContext.graphqlContext, ['logger', 'models']) : {})}`,
},
})).concat(middlewareLink).concat(new HttpLink({ uri, fetch }));
The middlewareLink has checkPermissions that returns true of false depending on user's role
const middlewareLink = new ApolloLink((operation, forward) => {
const { operationName } = operation;
if (operationName !== 'IntrospectionQuery') {
const { variables } = operation;
const context = operation.getContext().graphqlContext;
const hasAccess = checkPermissions({ operationName, context, variables });
if (!hasAccess) {
// ...
}
}
return forward(operation);
});
What should I do if hasAccess is false. I guess I don't need to forward the operation as at this point it's clear that a user does not have access to it
UPDATE
I guess what I need to do is to extend the ApolloLink class, but so far I didn't manage to return error
Don't know if anyone else needs this, but I was trying to get a NetworkError specifically in the onError callback using Typescript and React. Finally got this working:
const testLink = new ApolloLink((operation, forward) => {
let fetchResult: FetchResult = {
errors: [] // put GraphQL errors here
}
let linkResult = Observable.of(fetchResult).map(_ => {
throw new Error('This is a network error in ApolloClient'); // throw Network errors here
});
return linkResult;
});
Return GraphQL errors in the observable FetchResult response, while throwing an error in the observable callback will produce a NetworkError
After some digging I've actually figured it out. But I'm not quite sure if my approach is correct.
Basically, I've called forward with a subsequent map where I return an object containing errors and data fields. Again, I guess there's a better way of doing this (maybe by extending the ApolloLink class)
const middlewareLink = new ApolloLink((operation, forward) => {
const { operationName } = operation;
if (operationName !== 'IntrospectionQuery') {
const { variables } = operation;
const context = operation.getContext().graphqlContext;
try {
checkPermissions({ operationName, context, variables });
} catch (err) {
return forward(operation).map(() => {
const error = new ForbiddenError('Access denied');
return { errors: [error], data: null };
});
}
}
return forward(operation);
});

How to use onCall with aws-sdk-mock?

I would like let the mock method enable different responses for consecutive calls to the same method.
I found that Sinon has onCall, it allowed I can stub method like below,
let stubCall = sandbox.stub(Math, 'random');
stubCall.onCall(0).returns(Promise.resolve(0));
stubCall.onCall(1).returns(Promise.resolve(-1));
but I don't know how to let this work on AWS mock framework like this.
AWS.mock('CloudFormation', 'describeStacks', Promise.resolve(stackResponse));
I tried
AWS.mock('CloudFormation', 'describeStacks', Promise.resolve(stackResponse)).onCall(0).returns(Promise.resolve(res));
and
let mockCall = AWS.mock('CloudFormation', 'describeStacks', Promise.resolve(res));
mockCall.onCall(0).returns(Promise.resolve(res));
both of them didn't work.
I found people discuss this issue , mentioned since this aws-mock use sinon, it should able to use onCall. Is anyone use it successfully?
Since I use promise, I don't know what else I can do to return the different response for the same method has been called several times.
First, set the AWS SDK instance to be mocked
const sinon = require('sinon');
const AWS_Mock = require('aws-sdk-mock');
const AWS_SDK = require('aws-sdk');
AWSMock.setSDKInstance(AWS_SDK);
Configure stub that will be called
const stub = sinon.stub();
stub.onCall(0).returns(1);
stub.onCall(1).returns(2);
Mock Service method
Make sure that you're mocking the exact signature of the method.
AWSMock.mock('CloudFormation', 'describeStacks', function(params, cb) {
cb(null, stub());
});
Our Mocked method in action
const cf = new AWS_SDK.CloudFormation();
cf.describeStacks({}, (err, data) => {
if(err) {
console.err(err);
}
console.log(data); // 1
});
cf.describeStacks({}, (err, data) => {
if (err) {
console.err(err);
}
console.log(data); // 2
});

How do I unit test localStorage being undefined with Mocha/Sinon/Chai

I have 2 simple methods that abstract reading and writing to localStorage:
_readLocalStorage: function(key) {
if (window.localStorage && window.localStorage.getItem(key)) {
return JSON.parse(window.localStorage.getItem(key));
} else {
throw new Error('Could not read from localStorage');
}
},
_writeLocalStorage: function(key, data) {
try {
window.localStorage.setItem(key, JSON.stringify(data));
} catch (e) {
throw new Error('Could not write to localStorage');
}
},
Obviously, stubbing window.localStorage.getItem/setItem is simple. But what about the case where localStorage is undefined?
I've tried caching/unhinging window.localStorage (the second assertion):
describe('#_readLocalStorage', function() {
it('should read from localStorage', function() {
// set up
var stub1 = sinon.stub(window.localStorage, 'getItem')
.returns('{"foo": "bar"}');
// run unit
var result = service._readLocalStorage('foo');
// verify expectations
expect(result)
.to.eql({foo: 'bar'});
// tear down
stub1.restore();
});
it('should throw an error if localStorage is undefined', function() {
// set up
var cachedLocalStorage = window.localStorage;
window.localStorage = undefined;
// run unit/verify expectations
expect(service._readLocalStorage('foo'))
.to.throw(new Error('Could not write to localStorage'));
// tear down
window.localStorage = cachedLocalStorage;
});
});
This does not work however. Mocha/Chai seem not to catch the thrown error.
I've looked around a bit but can't find any way to handle this.
Your expect should be
expect(service._readLocalStorage.bind(service, 'foo'))
.to.throw(new Error('Could not write to localStorage'));
The way you have it you code calls service._readLocalStorage('foo') before expect is called. So it raises an exception that expect cannot handle. What expect needs to be able to deal with exceptions is a function that expect itself will call. Using service._readLocalStorage.bind(service, 'foo') creates a new function that when called without arguments (as expect does) will be equivalent to calling service._readLocalStorage('foo').
There's another problem with your test: your cleanup code will never execute. The assertion libraries report problems by raising JavaScript exceptions. So any code that follows a failed exception won't run unless the exception is specially handled. You could do:
it('should throw an error if localStorage is undefined', function() {
// set up
var cachedLocalStorage = window.localStorage;
window.localStorage = undefined;
// run unit/verify expectations
try {
expect(...)...;
expect(...)...;
...
}
finally {
// tear down
window.localStorage = cachedLocalStorage;
}
});
For more complex cases, you should use before, beforeEach, after, afterEach for setup and teardown.