Unit testing React component using Material UI Dialog - unit-testing

I am currently writing unit tests for my React + MaterialUi application.
In my application I have a Dialog. I want to make sure depending on what button pressed on the dialog:
<FlatButton
label="Cancel"
secondary={true}
onTouchTap={this._cancelDialog.bind(this)}
/>
<FlatButton
label="Submit"
primary={true}
onTouchTap={this._confirmDialog.bind(this)}
/>
that the internal state changes accordingly.
Unfortunately i cannot get ahold of the dialog content using
TestUtils.scryRenderedComponentsWithType(FlatButton)
or
scryRenderedComponentsWithTag("button")
and so on.
Any ideas on how that flow can be tested?
Update 1
So I can get the Dialog instance by calling TestUtils.scryRenderedComponentsWithType(Dialog). But I can not get the dialogs content. DOM wise the content does not render inside the view itself. Its rendered in a new created node on document level (div). So i tried this:
let cancelButton = window.document.getElementsByTagName("button")[0];
Simulate.click(cancelButton);
cancelButton in the case above is the correct DOM element. Simulate.click however does not trigger the components click function.
regards
Jonas

just ran into the same problem. I looked into the source code, and the Dialog component's render method actually creates an instance of the component RenderToLayer. this component behaves as a portal and breaks react's DOM tree by returning null in its' render function and instead appending directly to the body.
Luckily, the RenderToLayer component accepts the prop render, which essentially allows the component to pass to the portal a function to be called when it is in a render cycle. This means that we can actually manually trigger this event ourselves. It's not perfect, i admit, but after a few days of poking around trying to find a solution for this hack i am throwing in the towel and writing my tests like this:
var component = TestUtils.renderIntoDocument(<UserInteractions.signupDialog show={true}/>)
var dialog = TestUtils.renderIntoDocument(component.refs.dialog.renderLayer())
var node = React.findDOMNode(dialog)
and here is what my UserInteractions.signupDialog looks like:
exports.signupDialog = React.createClass({
...
render: function() {
var self = this;
return (
<div>
<Dialog
ref='dialog'
title="Signup"
modal={false}
actions={[
<Button
label="Cancel"
secondary={true}
onTouchTap={self.__handleClose}
/>,
<Button
label="Submit"
primary={true}
keyboardFocused={true}
onTouchTap={self.__handleClose}
/>
]}
open={self.props.show}
onRequestClose={self.__handleClose}
>
<div className='tester'>ham</div>
<TextField id='tmp-email-input' hintText='email' type='text'/>
</Dialog>
</div>
)
}
})
Now i can make assertions against the child components rendered in the dialog box, and can even make assertions about events bound to my original component, as their relationship is maintained.
I definitely recommend setting up a debugger in your testing stack if you are going to continue using material ui. Theres not a lot of help for things like this. Heres what my debug script looks like:
// package.json
{
...
"scripts": {
"test": "mocha --compilers .:./test/utils/compiler.js test/**/*.spec.js",
"debug": "mocha debug --compilers .:./test/utils/compiler.js test/**/*.spec.js"
}
}
and now you can use npm test to run mocha tests, and npm run debug to enter debugger. Once in the debugger, it will immediately pause and wait for you to enter breakpoints. At this juncture, enter c to continue. Now you can place debugger; statements anywhere in your code to generate a breakpoint which the debugger will respond to. Once it has located your breakpoint, it will pause and allow you to engage your code using local scope. At this point, enter repl to enter your code's local scope and access your local vars.
Perhaps you didnt need a debugger, but maybe someone else will find this helpful. Good luck, happy coding!

Solved it as follows:
/*
* I want to verify that when i click on cancel button my showModal state is set * to false
*/
//shallow render my component having Dialog
const wrapper= shallow(<MyComponent store={store} />).dive();
//Set showModal state to true
wrapper.setState({showModal:true});
//find out cancel button with id 'cancelBtn' object from actions and call onTouchTap to mimic button click
wrapper.find('Dialog').props().actions.find((elem)=>(elem.props.id=='cancelBtn')).props.onTouchTap();
//verify that the showModal state is set to false
expect(wrapper.state('showModal')).toBe(false);

I ran into the same issue and solve it like that :
const myMock = jest.genMockFunction();
const matcherComponent = TestUtils.renderIntoDocument(
<MatcherComponent onClickCancel={myMock} activAction/>
);
const raisedButton = TestUtils.findRenderedComponentWithType(
matcherComponent, RaisedButton);
TestUtils.Simulate.click(ReactDOM.findDOMNode(raisedButton).firstChild);
expect(myMock).toBeCalled();
It works fine for me. However I'm still struggling with Simulate.change

Solution by avocadojesus is excellent. But I have one addition. If you try to apply this solution and get an error:
ERROR: 'Warning: Failed context type: The context muiTheme is marked
as required in DialogInline, but its value is undefined.
You should modify his the code as follows:
var component = TestUtils.renderIntoDocument(
<MuiThemeProvider muiTheme={getMuiTheme()}>
<UserInteractions.signupDialog show={true}/>
</MuiThemeProvider>
);
var dialogComponent = TestUtils.findRenderedComponentWithType(component, UserInteractions.signupDialog);
var dialog = TestUtils.renderIntoDocument(
<MuiThemeProvider muiTheme={getMuiTheme()}>
{dialogComponent.refs.dialog.renderLayer()}
</MuiThemeProvider>
);
var node = React.findDOMNode(dialog);

Material UI fork the 2 enzyme methods. You need to use the createMount or the createShallow with dive option https://material-ui.com/guides/testing/#createmount-options-mount

Related

Attachments moved away from Item after validation and before submit process in Apex

I have multiple File Browser Item fields on one page of Application in Oracle Apex.
What happens: When I miss any Item for which validation error fires, I want to hold that file to the browser but I usually loose it if I get that validation error. Is there a solution for the same like other Items fields hold previous value except File Browser Item field. Please see below ss:
Anshul,
APEX 4.2 is very old and no longer supported. A later (or preferably latest) version of APEX will behave differently as Dan explained above.
Can you import your application into apex.oracle.com (which is running APEX 20.1) and you will probably see better results. Based on this you can hopefully use it as justification to upgrade your environment.
Regards,
David
Go to your page-level attributes and a function like the following in the Function and Global Variable Declaration:
function validateItems(request) {
var $file1 = $('#P68_FILE_1');
var $file2 = $('#P68_FILE_2');
var errorsFound = false;
if ($file1.val() === '') {
errorsFound = true;
// Show item in error state
}
if ($file2.val() === '') {
errorsFound = true;
// Show item in error state
}
if (!errorsFound) {
// I think doSubmit was the name of the function back then. If not, try apex.submit
doSubmit(request);
} else {
// Show error message at top of page, I'll use a generic alert for now
alert('You must select a file for each file selector.');
}
}
Then, right-click the Create button and select Create a Dynamic Action. Set the name of the Dynamic Action to Create button clicked.
For the Action, set Type to Execute JavaScript Code. Enter the following JS in code:
validateItems('CREATE');
Finally, ensure that Fire on Initialization is disabled.
Repeat the process for the Save button, but change the request value passed to validateItems to SAVE.

App with both SideDrawer and No Sidedrawer

I have a app working nicely with a sidedrawer, but would like to add pages without that menu.
The magic for launching a sidedrawer seems mostly in app.js:
new Vue({
render (h) {
return h(
App,
[
h(DrawerContent, { slot: 'drawerContent' }),
h(Home, { slot: 'mainContent' }
]
)
}
}).$start();
And we could launch a home page without that drawer:
render: h => h('frame', [h(Twisty)])}).$start();
But how to launch the sidedrawer menu later, after viewing the drawer-less pages?
OK, I may have been thinking about this wrong.
By making the 'menuless' page just another entry in DrawerContent.vue, and adding
android:visibility="collapsed"
ios:visibility="collapsed"
to that page's ActionItem, the page appears menuless. Then a nice
this.$navigateTo(Home);
gets us back to the regular sidebar navigation.
(I'd actually tried this before, and it was failing, but because I was calling YoutubePlayer in Preview, not for any sidebar related issue.)

In Semantic-UI-React, is there a way to add an x icon to a text input or dropdown that will clear the text when clicked?

I have both a text input and a dropdown that allows additions (both use the Form.xxx version). For both of these, I would like to add an x icon on the right, that when clicked, will either call a handler or will clear the input's value.
Is this possible in semantic-ui-react?
Thank you
I did find a solution, which I will share, but this means I can no longer have my lock icon on the left hand side, because an input can only have one icon.
What I've done is to use an Icon element, and add an onClick handler to that, as follows:
<Input ...
icon={<Icon name='delete' link onClick={this.handleDeleteClick}/>}/>
(Updated)
To clear the field, there is no "semantic-ui-react" shortcut as far as I know.
However, you can do this manually using your component state.
Here would be an example of this:
class ExampleClearField extends Component {
state = {}
handleChange = (e, { name, value }) => this.setState({ [name]: value })
handleClear = () => this.setState({ email: ''})
render() {
const { email } = this.state
return (
<Form.Input iconPosition='left' name="email />
<Icon name='x' link onClick={this.handleClear} />
<input/>
</Form.Input>
)
}
}
** Notice the link, which is needed for Icon to accept onClick.
Also, dont't forget about (you might need to change it's place depending on iconPostion)
As of Semantic UI React 0.83.0, it is possible to do this with Dropdowns using clearable. You cannot add your own event handler to the "x" by using this. Clicking the "x" will simply clear the selected value and call onChange with the new empty value.
Example from their docs:
const DropdownExampleClearable = () => <Dropdown clearable options={options} selection />
See the example output on their docs page here

data-dialog created dynamically

I'm using polymer 1.0.
I'm trying to open a with on a clic on an element created dynamically with template repeat.
Here is the code :
<paper-button
data-dialog="modal"
on-click="dialogClick">
Click
</paper-button>
and the script (from doc) :
dialogClick: function(e) {
var button = e.target;
while (!button.hasAttribute('data-dialog') && button !== document.body) {
button = button.parentElement;
}
if (!button.hasAttribute('data-dialog')) {
return;
}
var id = button.getAttribute('data-dialog');
var dialog = document.getElementById(id);
alert(dialog);
if (dialog) {
dialog.open();
}
}
This work only if the value of data-dialog is simple text. If I want to change it by data-dialog="{{item.dialogName}}" for instance, it doesn't work. It is not found by the while loop and exit with the if. in the source code of the page, there is no data-dialog in the paper-button.
Any idea ?
I've ran into a similar problem when using data attributes on custom elements. You might want to subscribe to this polymer issue.
As a workaround, place the data attribute in a standard element that is a parent of the button and search for that one instead.
Also, you might want to consider using var button = Polymer.dom(e).localTarget instead of directly accessing e.target, since the later will give you an element deeper in the dom tree under shady dom.

How change the event in [XTK]

Hello,
I wonder how do I change my mouse event
because I would like to X.Caption activates only when I right-clicked on it.
thank you very much
If I'm correct ( other contributors, don't be afraid to correct me ), you might have to edit the internals of XTK for your needs. XTK has the "controls" defined in X.event.js for it's event such as HoverEvent and PanEvent which are acquired from the Google Closure Library. You can look into the Google Closure Library more as I haven't completely reviewed it, but X.caption is mostly derived from Goog.ui.Tooltip which can be used with the events from Goog.ui.Popup, Goog.ui.PopupBase, and Goog.events. You can try to include Goog.events into your Javascript and define your own click event or something related to that and look through the Google Closure Library some more.
If what I just wrote in the small paragraph above is not completely correct or anything like that, there are of course basic Javascript DOM Events for clicking. I'm not quite sure how those would work with XTK because XTK uses WebGL for rendering. You can review the basic events at http://www.w3schools.com/jsref/dom_obj_event.asp. If you find any solution for yourself, you are more than welcome to contribute it to XTK.
I think there are too ways no ? Change the xtk source code and compile your own version or something like this :
window.onload = function() {
myrenderer.config.HOVERING_ENABLED = false; // disabling show caption on mousehover
var mouse_x, mouse_y;
myrenderer.interactor.onMouseMove = function(event) {
mouse_x = event.offsetX;
mouse_y = event.offsetY;
}
myrenderer.interactor.onMouseDown = function(left,middle, right) {
if (right) {
var picked_id = myrenderer.pick(mouse_x, mouse_y);
if (picked_id==-1) throw new Error("No object");
var picked_object = myrenderer.get(picked_id);
var mycontainer = myrenderer.container;
var caption = new X.caption(mycontainer,mycontainer.offsetLeft + mouse_x + 10, mycontainer.offsetTop + mouse_y + 10,myrenderer.interactor);
caption.setHtml(picked_object.caption);
// use settimeout or something else to destroy the caption
}
}
}
The following JSFiddle shows how to do that. To actually display a tooltip etc. you can use any JS Library like jQuery UI.
http://jsfiddle.net/haehn/ZpX34/