RTK Query running twice instead of once - react-redux

This is an authorizaton middleware component that wraps the App component in a React app using Redux Toolkit.
The authorization is done using an access_token cookie. There is a also a logged_in cookie with httponly=false so the client knows its logged in, and a refresh_token cookie.
The logic is:
check if there is a logged_in cookie, if not, finish
send a request to the GetWhoAmI api endpoint
GetWhoAmI success: finish
GetWhoAmI fail: try to refresh the access_token using the RefreshToken endpoint
RefreshToken fail: delete the logged_in cookie and finish
RefreshToken success: try the GetWhoAmI endpoint again
GetWhoAmI success: finish
GetWhoAmI fail: remove logged_in cookie and finish
I do not like this state machine approach, but I have tried everything else and I kept getting strange loops, or queries not running at all.
export const AuthMiddleware: React.FC<{ children: React.ReactElement }> =
({ children }) => {
const [state, setState] = useState(1);
const [cookie, , removeCookie] = useCookies(["logged_in"]);
const hasLoggedInCookie = cookie.logged_in === "true";
const { isSuccess: whoAmISuccess, isError: whoAmIError } =
useGetWhoAmIQuery(undefined, { skip: state !== 2 && state !== 4 });
const { isSuccess: refreshSuccess, isError: refreshError } =
useRefreshTokenQuery(undefined, { skip: state !== 3 });
if (state === 1) {
setState(hasLoggedInCookie ? 2 : 0);
}
if (state === 2 && whoAmIError) setState(3);
if (state === 2 && whoAmISuccess) setState(0);
if (state === 4 && whoAmISuccess) setState(0);
if (state === 4 && whoAmIError) {
removeCookie("logged_in");
setState(0);
}
if (state === 3 && refreshError) {
removeCookie("logged_in");
setState(0);
}
if (state === 3 && refreshSuccess) {
setState(4);
}
console.log(state);
if (state !== 0) {
return <FullScreenLoader />;
}
return children;
};
As far as functionality goes this works, but there are two strange issues:
When it gets to the point where the RefreshToken endpoint needs to be invoked, the endpoint is queried twice in a row.
If I log the state, it looks as the state goes backwards sometime, for example it goes 3-2-3 or 4-3-4, even though from the code it is not possible for the state to go from 4 to 3 or from 3 to 2.
There is obviously something I'm doing wrong here but after two days of banging my head against this problem I can't figure it out.

There is a refresh token approach in the documentation that lives in RTK Query, not in a component - have you tried that?
Automatic Reauthorization by extending fetchBaseQuery
Your code would come down to a single useGetWhoAmIQuery() call.
Also, something like a token refresh (if you choose this approach here) should always be a mutation, not a query. Then it could also invalidate the getWhoAmIQuery and it could automatically refetch - no need for you to orchestrate that!

Related

How to wait for a successful response in Cypress tests

Background
I use 3 back-end servers to provide fault tolerance for one of my online SaaS application. All important API calls, such as getting user data, contact all 3 servers and use value of first successfully resolved response, if any.
export function getSuccessValueOrThrow$<T>(
observables$: Observable<T>[],
tryUntilMillies = 30000,
): Observable<T> {
return race(
...observables$.map(observable$ => {
return observable$.pipe(
timeout(tryUntilMillies),
catchError(err => {
return of(err).pipe(delay(5000), mergeMap(_err => throwError(_err)));
}),
);
})
);
}
getSuccessValueOrThrow$ get called as following:
const shuffledApiDomainList = ['server1-domain', 'server2-domain', 'server3-domain';
const sessionInfo = await RequestUtils.getSuccessValueOrThrow(
...(shuffledApiDomainList.map(shuffledDomain => this.http.get<SessionDetails>(`${shuffledDomain}/file/converter/comm/session/info`))),
).toPromise();
Note: if one request resolve faster than others, usually the case, race rxjs function will cancel the other two requests. On Chrome dev network tab it will look like bellow where first request sent out was cancelled due to being too slow.
Question:
I use /file/converter/comm/session/info (lets call it Endpoint 1) to get some data related to a user. This request dispatched to all 3 back-end servers. If one resolve, then remaining 2 request will be cancelled, i.e. they will return null.
On my Cypress E2E test I have
cy.route('GET', '/file/converter/comm/session/info').as('getSessionInfo');
cy.visit('https://www.ps2pdf.com/compress-mp4');
cy.wait('#getSessionInfo').its('status').should('eq', 200)
This sometimes fails if the since getSessionInfo alias was hooked on to a request that ultimately get cancelled by getSuccessValueOrThrow$ because it wasn't the request that succeeded.Bellow image shows how 1 out of 3 request aliased with getSessionInfo succeeded but the test failed since the first request failed.
In Cypress, how do I wait for a successful i.e. status = 200 request?
Approach 1
Use .should() callback and repeat the cy.wait call if status was not 200:
function waitFor200(routeAlias, retries = 2) {
cy.wait(routeAlias).then(xhr => {
if (xhr.status === 200) return // OK
else if (retries > 0) waitFor200(routeAlias, retries - 1); // wait for the next response
else throw "All requests returned non-200 response";
})
}
// Usage example.
// Note that no assertions are chained here,
// the check has been performed inside this function already.
waitFor200('#getSessionInfo');
// Proceed with your test
cy.get('button').click(); // ...
Approach 2
Revise what it is that you want to test in the first place.
Chances are - there is something on the page that tells the user about a successful operation. E.g. show/hide a spinner or a progress bar, or just that the page content is updated to show new data fetched from the backend.
So in this approach you would remove cy.wait() altogether, and focus on what the user sees on the page - do some assertions on the actual page content.
cy.wait() yields an object containing the HTTP request and response properties of the XHR. The error you're getting is because you're looking for property status in the XHR object, but it is a property of the Response Object. You first have to get to the Response Object:
cy.wait('#getSessionInfo').should(xhr => {
expect(xhr.response).to.have.property('status', 200);
});
Edit: Since our backend uses graphql, all calls use the single /graphql endpoint. So I had to come up with a solution to differentiate each call.
I did that by using the onResponse() method of cy.route() and accumulating the data in Cypress environment object:
cy.route({
method: 'GET',
url: '/file/converter/comm/session/info',
onResponse(xhr) {
if (xhr.status === 200) {
Cypress.env('sessionInfo200') = xhr;
}
}
})
You can then use it like this:
cy.wrap(Cypress.env()).should('have.property', 'sessionInfo200');
I wait like this:
const isOk = cy.wait("#getSessionInfo").then((xhr) => {
return (xhr.status === 200);
});

Unit testing NestJS Observable Http Retry

I'm making a request to a 3rd party API via NestJS's built in HttpService. I'm trying to simulate a scenario where the initial call to one of this api's endpoints might return an empty array on the first try. I'd like to use RxJS's retryWhen to hit the api again after a delay of 1 second. I'm currently unable to get the unit test to mock the second response however:
it('Retries view account status if needed', (done) => {
jest.spyOn(httpService, 'post')
.mockReturnValueOnce(of(failView)) // mock gets stuck on returning this value
.mockReturnValueOnce(of(successfulView));
const accountId = '0812081208';
const batchNo = '39cba402-bfa9-424c-b265-1c98204df7ea';
const response =client.viewAccountStatus(accountId, batchNo);
response.subscribe(
data => {
expect(data[0].accountNo)
.toBe('0812081208');
expect(data[0].companyName)
.toBe('Some company name');
done();
},
)
});
My implementation is:
viewAccountStatus(accountId: string, batchNo: string): Observable<any> {
const verificationRequest = new VerificationRequest();
verificationRequest.accountNo = accountId;
verificationRequest.batchNo = batchNo;
this.logger.debug(`Calling 3rd party service with batchNo: ${batchNo}`);
const config = {
headers: {
'Content-Type': 'application/json',
},
};
const response = this.httpService.post(url, verificationRequest, config)
.pipe(
map(res => {
console.log(res.data); // always empty
if (res.status >= 400) {
throw new HttpException(res.statusText, res.status);
}
if (!res.data.length) {
this.logger.debug('Response was empty');
throw new HttpException('Account not found', 404);
}
return res.data;
}),
retryWhen(errors => {
this.logger.debug(`Retrying accountId: ${accountId}`);
// It's entirely possible the first call will return an empty array
// So we retry with a backoff
return errors.pipe(
delayWhen(() => timer(1000)),
take(1),
);
}),
);
return response;
}
When logging from inside the initial map, I can see that the array is always empty. It's as if the second mocked value never happens. Perhaps I also have a solid misunderstanding of how observables work and I should somehow be trying to assert against the SECOND value that gets emitted? Regardless, when the observable retries, we should be seeing that second mocked value, right?
I'm also getting
: Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error:
On each run... so I'm guessing I'm not calling done() in the right place.
I think the problem is that retryWhen(notifier) will resubscribe to the same source when its notifier emits.
Meaning that if you have
new Observable(s => {
s.next(1);
s.next(2);
s.error(new Error('err!'));
}).pipe(
retryWhen(/* ... */)
)
The callback will be invoked every time the source is re-subscribed. In your example, it will call the logic which is responsible for sending the request, but it won't call the post method again.
The source could be thought of as the Observable's callback: s => { ... }.
What I think you'll have to do is to conditionally choose the source, based on whether the error took place or not.
Maybe you could use mockImplementation:
let hasErr = false;
jest.spyOn(httpService, 'post')
.mockImplementation(
() => hasErr ? of(successView) : (hasErr = true, of(failView))
)
Edit
I think the above does not do anything different, where's what I think mockImplementation should look like:
let err = false;
mockImplementation(
() => new Observable(s => {
if (err) {
s.next(success)
}
else {
err = true;
s.next(fail)
}
})
)

How do you store a custom 404 page on the client/browser to show when there's no internet connection? [duplicate]

I have a service worker that is supposed to cache an offline.html page that is displayed if the client has no network connection. However, it sometimes believes the navigator is offline even when it is not. That is, navigator.onLine === false. This means the user may get offline.html instead of the actual content even when online, which is obviously something I'd like to avoid.
This is how I register the service worker in my main.js:
// Install service worker for offline use and caching
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js', {scope: '/'});
}
My current service-worker.js:
const OFFLINE_URL = '/mysite/offline';
const CACHE_NAME = 'mysite-static-v1';
self.addEventListener('install', (event) => {
event.waitUntil(
// Cache the offline page when installing the service worker
fetch(OFFLINE_URL, { credentials: 'include' }).then(response =>
caches.open(CACHE_NAME).then(cache => cache.put(OFFLINE_URL, response)),
),
);
});
self.addEventListener('fetch', (event) => {
const requestURL = new URL(event.request.url);
if (requestURL.origin === location.origin) {
// Load static assets from cache if network is down
if (/\.(css|js|woff|woff2|ttf|eot|svg)$/.test(requestURL.pathname)) {
event.respondWith(
caches.open(CACHE_NAME).then(cache =>
caches.match(event.request).then((result) => {
if (navigator.onLine === false) {
// We are offline so return the cached version immediately, null or not.
return result;
}
// We are online so let's run the request to make sure our content
// is up-to-date.
return fetch(event.request).then((response) => {
// Save the result to cache for later use.
cache.put(event.request, response.clone());
return response;
});
}),
),
);
return;
}
}
if (event.request.mode === 'navigate' && navigator.onLine === false) {
// Uh-oh, we navigated to a page while offline. Let's show our default page.
event.respondWith(caches.match(OFFLINE_URL));
return;
}
// Passthrough for everything else
event.respondWith(fetch(event.request));
});
What am I doing wrong?
navigator.onLine and the related events can be useful when you want to update your UI to indicate that you're offline and, for instance, only show content that exists in a cache.
But I'd avoid writing service worker logic that relies on checking navigator.onLine. Instead, attempt to make a fetch() unconditionally, and if it fails, provide a backup response. This will ensure that your web app behaves as expected regardless of whether the fetch() fails due to being offline, due to lie-fi, or due to your web server experiencing issues.
// Other fetch handler code...
if (event.request.mode === 'navigate') {
return event.respondWith(
fetch(event.request).catch(() => caches.match(OFFLINE_URL))
);
}
// Other fetch handler code...

How to repeat, circle XHR requests, handle multiple XHR requests in Cypress

How to make through an interval requests before tests?
I tried 2 ways to retry requests but either was failing;
I need to upload a file, waiting till one got imported successfully
On the first step i upload a file to my server in cypress
before( ()=> {
//my custom POST command
cy.form_request(url, data)
.then(({id}) => {
Then i wait for id of the uploaded file
check_It_Till_Success_It(id);
})
})
Then the received id i pass into a new request to verified its status on the server and need to repeat the request till the file processing is finished.
At the solution below it says
CypressError: cy.wait() only accepts aliases for routes.
The alias: 'check_it_request' did not match a route.
function check_It_Till_Success_It(id) {
function checkRequest() {
cy.request("GET", "http://localhost:28080/admin/api/catalog/import/status/" + id)
.then(({status}) => {
if (status === "FINISHED" || status === "FAILED") {
clearInterval(check_It);
} else {
console.log('retry one more time');
}
}).as('check_it_request');
cy.wait("#check_it_request");
}
checkRequest();
const check_It = setInterval(checkRequest, 1000);
}
or here is another my solution through a recursive requesting:
function check_It_Till_Success_It(id) {
return (
cy.request("GET", BASE_URL + "/admin/api/catalog/import/status/" + id)
.then(({status}) => {
if (status === "FINISHED" || status === "FAILED") {
console.log('success');
} else {
console.log('retry one more time');
setTimeout(() => check_It_Till_Success_It(id), 1000)
}
})
)
}
but it throws an error:
Uncaught CypressError: Cypress detected that you returned a promise from a command while also invoking one or more cy commands in that promise.
What am i doing wrong?
I found my mystake because of the use of native JS tools as setTimeout, setInterval.
Cypress doesnt allow to use them and replaces with controllable methods: cy.clock and cy.tick
So i took the recursion implementation and replaced with the methods above and my code became:
function check_It_Till_Success_It(id) {
cy.request("GET", BASE_URL + "/admin/api/catalog/import/status/" + id)
.then(resp => {
const status = resp.body.status;
if (status === "FINISHED" || status === "FAILED") {
console.log('success');
} else {
console.log('retry one more time');
cy.clock();
cy.tick(1000);
check_It_Till_Success_It(id)
}
})
}
Offtopic note: I'm new with Cypress and as i understood it replaces the most of the js native features so it's needed to look the docs much closer (BINGO!) or look at issue section because some JS specific feature just crash Cypress without any notification or catched error, for example: FormData object crashed Cypress'es request method.

testing custom redux middleware, which handles ajax request

I am building a react-redux app, using custom redux middleware.
In the definition of my project, action only provides an object to define action type and necessary parameters for middleware and reducer. All the ajax request will be handle by middleware. This is the life cycle would look like:
action -> middleware(if action is intercepted) -> reducer -> store
When the user tries to log in, the operation on the react component will fire an action, which would look like this:
export function login(username, password) {
return {
type: 'LOGIN',
username: username,
password: password
}
}
export function authSucceed(username, isAdmin) {
return {
type: 'AUTHSUCCEED',
username: username,
isAdmin: isAdmin
}
}
export function authFail(text) {
return {
type: 'AUTHFAIL',
errorMessage: text
}
}
Then middleware will use the parameters passed in action to send ajax request, which would be like this.
export function customedMiddleware(store) {
return next => action => {
if (action.type === 'LOGIN') {
axios.post(url + '/api/login', {
username: action.username,
password: action.password
})
.then(res => {
if (res.status === 200) {
store.dispatch(actions.authSucceed(res.data.username, res.data.isAdmin));
} else {
store.dispatch(actions.authFail(res.data));
}
})
.catch(error => console.log(error));
}
return next(action);
};
}
After the middleware sends login request to server, depending on whether the authentication succeeds or not, the middleware will dispatch some action in reducer correspondingly. Since authSucceed and authFail would not be intercepted by middleware, reducer will process accordingly.
export default function(state = false, action) {
switch(action.type) {
case 'AUTHSUCCEED':
return true;
case 'AUTHFAIL':
return false;
case 'LOGOUT':
return false;
}
return state;
}
What has been done here in reducer is to change the system state. If the state is true, the front-end will render the information page. If the state is false, the front-end will remain in the login page.
I like system definition this way. Every MVC part is well isolated. However, it's very difficult to test the middleware. Currently, I am testing this way:
it('should dispatch authSucceed if signup with correct info', () => {
nock('http://localhost:8080')
.post('/api/signup', {
username: 'bruce',
password: 'Gx1234'
})
.reply(200, {
username: 'bruce',
isAdmin: false
});
const createStoreWithMiddleware = applyMiddleware(customedMiddleware)(createStore);
const store = createStoreWithMiddleware(reducers);
const dispatch = sinon.spy(store, 'dispatch');
store.dispatch(actions.login('bruce', 'Gx1234'));
setTimeout(() => {
expect(dispatch.calledWith({
type: 'AUTHSUCCEED',
username: 'bruce',
isAdmin: false
})).to.be.true;
}, 100);
});
I dispatch login action. Then spy the whether authSucceed action and authFail action will be called correctly within 100ms. This method works if there is only one test to be run. If there are more then one test running in sequence, they might affect each other. I have to adjust the time delay of the setTimeout to make it work for all cases, which is 10ms.
I don't feel comfortable this way. I can't make sure whether it just work for me or for everybody too, since absolute time is related to hardware.
I would really appreciate if anybody can give me some advice on how to test this custom middleware.
Your code works fine, but you shouldn't need a setTimeout with such a long time since using nock makes the remote resquest response instantly. The problem is promises enqueue microtasks and they only run after a macrotask is finished (in your case, it()), in the same event loop.
That's why you need setTimeout to enqueue another macrotask, the time doesn't make a difference. I believe setImmediate should work as well.

Resources