React Testing Library for Actions in redux - react-testing-library

I am new to React Testing Library and have issue with actions.
Can anyone please guide me
I have tried below code and its giving error Received: [Function anonymous]
export const openText = () => (dispatch: Dispatch) => {
dispatch({
type: actionTypes.Text,
payload: true
});
};
Test Case
it('open text() => {
const expectedAction = {
type: actionTypes.OPEN_Text,
payload:'value
};
const action = actions.openText('value);
expect(action).toEqual(expectedAction);
});
Error: It says Received: [Function anonymous]

React Testing Library, as the name implies, is used for testing React components. You do not need it in this case.
You seem to be trying to test a Redux action creator. I suggest you follow the async action creators section from the Redux docs.
Your test currently fails because you are expecting to receive an object but your action creator returns a function.

Related

Mocking authentication when testing MSAL React Apps

Our app is wrapped in the MSAL Authentication Template from #azure/msal-react in a standard way - key code segments are summarized below.
We would like to test app's individual components using react testing library (or something similar). Of course, when a React component such as SampleComponentUnderTest is to be properly rendered by a test as is shown in the simple test below, it must be wrapped in an MSAL component as well.
Is there a proper way to mock the MSAL authentication process for such purposes? Anyway to wrap a component under test in MSAL and directly provide test user's credentials to this component under test? Any references to useful documentation, blog posts, video, etc. to point us in the right direction would be greatly appreciated.
A Simple test
test('first test', () => {
const { getByText } = render(<SampleComponentUnderTest />);
const someText = getByText('A line of text');
expect(someText).toBeInTheDocument();
});
Config
export const msalConfig: Configuration = {
auth: {
clientId: `${process.env.REACT_APP_CLIENT_ID}`,
authority: `https://login.microsoftonline.com/${process.env.REACT_APP_TENANT_ID}`,
redirectUri:
process.env.NODE_ENV === 'development'
? 'http://localhost:3000/'
: process.env.REACT_APP_DEPLOY_URL,
},
cache: {
cacheLocation: 'sessionStorage',
storeAuthStateInCookie: false,
},
system: {
loggerOptions: {
loggerCallback: (level, message, containsPii) => {
if (containsPii) {
return;
}
switch (level) {
case LogLevel.Error:
console.error(message);
return;
case LogLevel.Info:
console.info(message);
return;
case LogLevel.Verbose:
console.debug(message);
return;
case LogLevel.Warning:
console.warn(message);
return;
default:
console.error(message);
}
},
},
},
};
Main app component
const msalInstance = new PublicClientApplication(msalConfig);
<MsalProvider instance={msalInstance}>
{!isAuthenticated && <UnauthenticatedHomePage />}
{isAuthenticated && <Protected />}
</MsalProvider>
Unauthenticated component
const signInClickHandler = (instance: IPublicClientApplication) => {
instance.loginRedirect(loginRequest).catch((e) => {
console.log(e);
});
};
<UnauthenticatedTemplate>
<Button onClick={() => signInClickHandler(instance)}>Sign in</Button>
</UnauthenticatedTemplate>
Protected component
<MsalAuthenticationTemplate
interactionType={InteractionType.Redirect}
errorComponent={ErrorComponent}
loadingComponent={LoadingComponent}
>
<SampleComponentUnderTest />
</MsalAuthenticationTemplate>
I had the same issue as you regarding component's test under msal-react.
It took me a couple of days to figure out how to implement a correct auth mock.
That's why I've created a package you will find here, that encapsulates all the boilerplate code : https://github.com/Mimetis/msal-react-tester
Basically, you can do multiple scenaris (user is already logged, user is not logged, user must log in etc ...) in a couple of lines, without having to configure anything and of course without having to reach Azure AD in any cases:
describe('Home page', () => {
let msalTester: MsalReactTester;
beforeEach(() => {
// new instance of msal tester for each test
msalTester = new MsalReactTester();
// spy all required msal things
msalTester.spyMsal();
});
afterEach(() => {
msalTester.resetSpyMsal();
});
test('Home page render correctly when user is logged in', async () => {
msalTester.isLogged();
render(
<MsalProvider instance={msalTester.client}>
<MemoryRouter>
<Layout>
<HomePage />
</Layout>
</MemoryRouter>
</MsalProvider>,
);
await msalTester.waitForRedirect();
let allLoggedInButtons = await screen.findAllByRole('button', { name: `${msalTester.activeAccount.name}` });
expect(allLoggedInButtons).toHaveLength(2);
});
test('Home page render correctly when user logs in using redirect', async () => {
msalTester.isNotLogged();
render(
<MsalProvider instance={msalTester.client}>
<MemoryRouter>
<Layout>
<HomePage />
</Layout>
</MemoryRouter>
</MsalProvider>,
);
await msalTester.waitForRedirect();
let signin = screen.getByRole('button', { name: 'Sign In - Redirect' });
userEvent.click(signin);
await msalTester.waitForLogin();
let allLoggedInButtons = await screen.findAllByRole('button', { name: `${msalTester.activeAccount.name}` });
expect(allLoggedInButtons).toHaveLength(2);
});
I am also curious about this, but from a slightly different perspective. I am trying to avoid littering the code base with components directly from msal in case we want to swap out identity providers at some point. The primary way to do this is to use a hook as an abstraction layer such as exposing isAuthenticated through that hook rather than the msal component library itself.
The useAuth hook would use the MSAL package directly. For the wrapper component however, I think we have to just create a separate component that either returns the MsalProvider OR a mocked auth provider of your choice. Since MsalProvider uses useContext beneath the hood I don't think you need to wrap it in another context provider.
Hope these ideas help while you are thinking through ways to do this. Know this isn't a direct answer to your question.

axios / jest - unabled to perform a call request (TypeError: Cannot read property 'then' of undefined)

I'm struggling to perform a test with jest concerning an axios api call
here is my API call, that works perfectly within my program
import axios from 'axios';
import crypto from 'crypto';
import { prop } from 'ramda';
const baseUrl = 'http://gateway.marvel.com:80';
const uri = '/v1/public/characters';
const charactersUrl = baseUrl + uri;
const timestamp = [Math.round(+new Date() / 1000)];
const privateApi = 'XXX';
const publicApi = 'XXX';
const concatenatedString = timestamp.concat(privateApi, publicApi).join('');
const hash = crypto.createHash('md5').update(`${concatenatedString}`).digest('hex');
const charactersApi = () =>
axios
.get(charactersUrl, {
params: {
ts: timestamp,
apikey: publicApi,
hash,
},
})
.then(prop('data'));
export default charactersApi;
When I'm trying to test it, that way:
import axiosMock from 'axios';
import charactersApi from '../marvelApi';
jest.mock('axios', () => ({
get: jest.fn(),
}));
describe('tools | marvelApi', () => {
const piece = { name: '3D-MAN' };
axiosMock.get.mockResolvedValueOnce({ data: piece });
it('should get the character', () => {
return charactersApi().then(elem => {
expect(elem.name).toEqual('3D-MAN');
});
});
});
I get the following message from jest
TypeError: Cannot read property 'then' of undefined
16 |
17 | const charactersApi = () =>
> 18 | axios
| ^
19 | .get(charactersUrl, {
20 | params: {
21 | ts: timestamp,
at charactersApi (src/tools/marvelApi.js:18:3)
at Object.<anonymous> (src/tools/tests/marvelApi.test.js:13:12)
What I have tried
A common error is to forget the return statement within the function that contain the request API, in my case it's done correctly (first piece of code -> charactersApi()) source1, source2
I also tried to return a Promise from the mocked Axios as I have seen on another SO ticket
jest.mock('axios', () => ({
get: jest.fn(() => Promise.resolve()),
}));
I think my axios mock is not correct, because the struggle comes from the test while the production version work well
Any thoughts ?
You can spy on the "axios.get" calls and resolve them to a fixed (mocked) value:
/**
* #jest-environment jsdom
*/
const axios = require('axios')
beforeAll(() => {
jest.spyOn(axios, 'get').mockImplementation()
})
afterAll(() => {
jest.restoreAllMocks()
})
it('returns the mocked response', async () => {
axios.get.mockResolvedValue({ data: 'foo' })
const res = await axios.get('https://api.github.com')
expect(res).toEqual({ data: 'foo' })
})
You shouldn't use jest.mock because it mocks a module that your imported code may be using. As far as I know, it doesn't affect the current module's imports (and you import axios as a part of your test).
Recommended solution
I strongly discourage you from spying/mocking axios directly. See my argumentation below.
You're mocking implementation details of axios. In other words, you take the axios.get function and throw it away, alongside any internal logic it may have, and replace it with a hard mock. This means your test no longer uses axios, instead it uses an emptied mocked shell of axios. This makes your test different from your actual code, which, in turn, decreases the confidence such a test gives you.
You're coupling your mocks with a specific request client (axios). Such an approach is not a long-term investment, as you're writing axios-specific mocks. You can't reuse such mocks for requests made by other clients (i.e. window.fetch, Apollo, etc.), because they have their own implementation details (i.e. window.fetch has no .get() to spy on), which only encourages you to write more implementation-specific logic in tests.
You can learn more about the disadvantages of direct mocking of request clients in the Stop mocking fetch article by Kent C. Dodds. It uses window.fetch mocks as an example, but you may replace it with ANY_REQUEST_CLIENT when reading.
I highly recommend using tools like Mock Service Worker (MSW) that will encourage you to write abstracted mocks that don't rely on any request clients (you can use them no matter how your tested code makes a request) and can even be reused across different testing levels (the same mocks for Jest, Storybook, or Cypress).
Here's how your test would look like with MSW:
import { rest } from 'msw'
import { setupServer } from 'msw/node'
import charactersApi from '../marvelApi';
const server = setupServer(
rest.get('http://gateway.marvel.com:80/v1/public/characters', (req, res, ctx) => {
return res(ctx.json({
data: {
name: '3D-MAN'
}
}))
})
)
beforeAll(() => server.listen()
afterAll(() => server.close())
describe('tools | marvelApi', () => {
it('should get the character', () => {
return charactersApi().then(elem => {
expect(elem.name).toEqual('3D-MAN')
})
})
})
Notice how there are no details about how the request is made, only which request to intercept and mock its response.
You can follow a detailed tutorial on how to Get started with MSW. There's also a great video on API mocking and what problems MSW solves.

conv.askToDeepLink is not a function

The old way of invoke the askToDeepLink are no more working in DialogFlow even in V1.
app.askToDeepLink('Great! Looks like we can do that in the Android app.', 'tool for Android',
'sample://scheduleMeeting', 'com.sample', 'handle this for you');
Anybody know the way to invoke askToDeepLink in V2?
If you are trying to connect one of your Android apps with your Assistant app, you should try this.
app.intent('ask_to_deep_link_detail', (conv) => {
const options = {
destination: 'Google',
url: 'example://gizmos',
package: 'com.example.gizmos',
reason: 'handle this for you',
};
conv.ask('Great! looks like maybe we can do that in the app.');
conv.ask(new DeepLink(options));
});
Getting the results of the helper
If the user accepts the link, the dialog with your app will end and you will not receive further requests. If they reject the link, you will receive another request with the intent actions.intent.LINK and a status argument:
app.intent('ask_to_deep_link_confirmation', (conv, params, response) => {
conv.ask('Okay maybe we can take care of that another time.');
});
I hope this helps.

RESTful Chromless implementation

I am looking for a way to use headless chrome similar to what chromeless does but instead of being implemented as a nodejs endpoint, allowing restful requests with the html content as a payload.
I want to run this service on aws lambda being triggered through API Gateway. Does anyone have experience with this usecase?
There's nothing keeping you from using Chromeless in your use-case. Chromeless can be used within an AWS Lambda function. You can take a (RESTful) request coming from AWS API Gateway and then do something with it and Chromeless. You can combine the #serverless-chrome/lambda package with Chromeless to get headless Chrome running within Lambda so that Chrome is available to Chromeless. The Chromeless Proxy works in a similar way. For example, your Lambda function's code might look like (this is untested code I just cobbled together, but should convey the idea):
const launchChrome = require('#serverless-chrome/lambda')
const Chromeless = require('chromeless').Chromeless
module.exports.handler = function handler (event, context, callback) {
const body = JSON.parse(event.body) // event.body coming from API Gateway
const url = body.url
const evaluateJs = body.evaluateJs
launchChrome({
flags: ['--window-size=1280x1696', '--hide-scrollbars'],
})
.then((chrome) => {
// Chrome is now running on localhost:9222
const chromeless = new Chromeless({
launchChrome: false,
})
chromeless
.goto(url)
.wait('body')
.evaluate(() => `
// this will be executed in headless chrome
${evaluateJs}
`)
.then((result) => {
chromeless
.end()
.then(chrome.kill) // https://github.com/adieuadieu/serverless-chrome/issues/41#issuecomment-317989508
.then(() => {
callback(null, {
statusCode: 200,
body: JSON.stringify({ result })
})
})
})
.catch(callback)
})
.catch((error) => {
// Chrome didn't launch correctly
callback(error)
})
}
You'll find a similar thread on the Chromeless Issue tracker here.
Disclosure: I'm a collaborator/author of these packages.

Unknown provider error when injecting factory

I am using yeoman angular full stack generator. Trying out ToDo items tutorial with MongoDB.
Everything worked fine i.e. I was able to read from DB using $http.get. However I decided to go further and create a factory so I can perform CURD.
After creating factory I tried to inject it but getting error as follows:
Error: [$injector:unpr] Unknown provider: factToDoProvider <- factToDo
http://errors.angularjs.org/1.2.6/$injector/unpr?p0=factToDoProvider%20%3C-NaNactToDo
at http://localhost:9000/bower_components/angular/angular.js:78:12
at http://localhost:9000/bower_components/angular/angular.js:3538:19
at Object.getService [as get] (http://localhost:9000/bower_components/angular/angular.js:3665:39)
at http://localhost:9000/bower_components/angular/angular.js:3543:45
at getService (http://localhost:9000/bower_components/angular/angular.js:3665:39)
at invoke (http://localhost:9000/bower_components/angular/angular.js:3687:13)
at Object.instantiate (http://localhost:9000/bower_components/angular/angular.js:3708:23)
at http://localhost:9000/bower_components/angular/angular.js:6758:28
at link (http://localhost:9000/bower_components/angular-route/angular-route.js:897:26)
at nodeLinkFn (http://localhost:9000/bower_components/angular/angular.js:6212:13)
Main.js controller looks like
'use strict';
angular.module('angularFsApp')
.controller('MainCtrl', function ($scope, $http, factToDo) {
$http.get('/api/awesomeThings').success(function(awesomeThings) {
$scope.awesomeThings = awesomeThings;
});
$http.get('/todo/todoItems').success(function(todoItems) {
$scope.todoItems = todoItems;
});
//$scope.newtodoItems = factToDo.getAllItems();
});
Where factToDo is my factory which look like as follows (todo.js)
angular.module('angularFsApp')
.factory('factToDo', function() {
return {
getAllItems: function () {
return [
{description: 'Hello World 1', priority: '15'},
{description: 'Hello World 2', priority: '15'},
{description: 'Love for all', priority: '1500'}
];
}
}
});
I tried by changing my code in main.js as described in AngularJS error ref as follows
angular.module('angularFsApp')
.controller('MainCtrl', ['$scope', '$http', 'factToDo', function ($scope, $http, factToDo) {
as well as I tried Dan Wahlin but i got same issue.
Make sure the file with the 'factToDo' is included into your app.
For a convenient development and to avoid issues like this in the future try the Grunt task runner to concatenate all your code for you and include it as a one file.
This tutorial seems to be sufficient for starting with Grunt and file concatenation.