How to assert with chai that some div contains some text? - assert

How to assert with chai that some div('.MyDive') contains text 'Some text'?
<div class="MyDive">
<div>Some text</div>
</div>

You'll want to pull in jQuery to access elements on the DOM. Once you have that, you can assert against DOM elements using vanilla Chai like so:
expect($('div.MyDive').text()).to.have.string('Some text');
If you want to visually clean up your code a bit, you could also pull in a plugin like chai-jquery and use a custom assertion, such as contain(text):
expect($('div.MyDive')).to.contain('Some text');

If you are using chai with WebdriverIO, you can do something like
expect = require('chai').expect;
client
.element('.MyDive')
.getText()
.then(function (text) {
expect(text).to.equal('Some text');
});

I prefer to use chai-dom for this:
import chai, { expect } from "chai";
import chaiDom from "chai-dom";
chai.use(chaiDom);
expect(document.querySelector(".MyDive")).to.have.text("Some text");

Related

Separate part of script tag in DOM on loading page by regex

I want to separate part of DOM that contain Javascript tag with variable named matchData that is a Object like below in laravel:
<div>
some data
<div>
<script type="text/javascript">
var matchData = {
sportId: 0,
id: 80302,
host: {
id: 921587,
name: "نفت‌
}
}
</script>
<div>
some data
<div>
<script>
...
</script>
i want to get matchData value by regex.
i try this:
/\bmatchData\s*=\s*(.+)(?=;|<\/script>)/
but it just work when there isnt any new line or tab in the dom. how can i get matchData by regex?
Regex is not well suited to this task! An HTML parser is a much, much better option. That being said, if you're dead-set on using regex, this may work: var matchData[\s\S]*?(?=<\/script>)
This starts matching at a var named matchData, and then continues matching until it hits the end of the first </script> tag. This solution is wildly inflexible and can be easily broken in a number of ways (such as if </script> is in the name), but if it's for a quick-and-dirty project and you don't care about maintainable code, it'll suit your needs.
Demo

Trouble unit testing onClick method using Mocha Chai and Enzyme

I'm having trouble with unit testing using mocha, chai and enzyme for the following. I can't seem to understand how to unit test methods in components and how to unit test onClick methods will call those methods.
The following is what I am trying to unit test:
<Link to="/create-new-template-results" onClick={this.checkLink}>
<Button
buttonname="Next_button"
variant="primary"
label="Save"
onClickMethod={() => this.submitTemplateCreation()}
disabled={!this.disabledButtonCheck()}
/>
</Link>
.
Header: '',
Cell: value => {
return (
<div>
<img
height={34}
src="https://content.usaa.com/mcontent/static_assets/Media/icon-trash.svg"
onClick={() => this.removeAttribute(value)}
/>
</div>
);
}
.
removeAttribute = value => {
this.props.change('templateAttributeForm', value.original.name, '');
this.props.removeAttributeItem(value.index);
};
submitTemplateCreation() {
let profLvlData = Object.values(this.props.templateAttributeFormData);
let attrData = Object.keys(this.props.templateAttributeFormData);
let attributeProfLvl = attributeProfLvlUtil(attrData, profLvlData);
let templateCreationJSON = templateCreationPOSTFilter(attributeProfLvl, this.props.templateFormData);
this.props.submitTemplateCreation(templateCreationJSON);
}
Chai provides some nice tools for testing things exactly like what you are talking about.
You'll want to render your component somehow in the virtual DOM, either by using enzyme's "shallow" or "mount" functions.
Once you've done that, you can access the component using .find, and "simulate" an event using .simulate like so.
wrapper.find('Button').at(0).simulate('click');
This will find all of the 'Button' components in your wrapper, take the first one, and simulate a click. From there you can use expect() combined with any of the ways Chai provides to examine the state of the component in order to test that your button did what it was supposed to.
Since it seems like you are particularly interesting in the calling of the onClick function itself, I will add that you can specifically check to see if a function is called by doing the following with Chai.
expect(MyComponent.prototype.myOnClickFunction).to.have.property('callCount', 1);

How can I access inline style using React findDomNode function?

I am currently Jest to test React component, component's inline style would be changed according to different props value.
this is an example about what I wanna do:
let firstChild = TestUtils.findRenderedDOMComponentWithTag(renderedComponent, 'div');
expect(firstChild.getDOMNode().style).toEqual({
fontSize: '20px'
});
This is the component props:
let renderedComponent = TestUtils.renderIntoDocument(
<CircleIcon
size="small" />
And this is the component dom to test with:
return (
<div className="circle-icon" style={boxStyle}>
<span className={this.props.icon}></span>
</div>
);
If I can get what is inside boxStyle, I can assert the test result from it.
Thanks a lot!
actually it works.
usage:
firstChild.getDOMNode().style.backgroundColor

polymer unit test mocking dependencies

Im just starting on polymer. Im trying to unit test a custom element that has dependencies and I would like to fake/mock these out.
I've found Scott Miles recommendation on how to mock the core-ajax implementation. I thought I could follow that pattern easily but this only works as long as my element does not import the about to be mocked (core-ajax in this case) element.
If it does import it, then when the test tries to run I get
'Uncaught NotSupportedError: Failed to execute 'registerElement' on 'Document': Registration failed for type 'core-ajax'. A type with that name is already registered.'
If I could do something like document.unregister the core-ajax element and import it again in my test, Id be a much happier dev!!!
Polymer is awesome but if I can not unit test it, then it presents major risks (at least when building an app that will need to be maintained/changed)
How are you guys working around this? I've been digging into Polymer and PolymerLab elements repo and most of them lack tests. So far I;ve not found much reference on how to do it.
Thanks for the help!
Santiago
Scotts' recommendation was:
Instead of importing core-ajax/core-ajax.html, create your own core-ajax element.
<polymer-element name="core-ajax" attributes="response">
<script>
Polymer('core-ajax', {
attached: function() {
this.response = ['a', 'b', 'c'];
}
});
</script>
</polymer-element>
Obviously, this is just an example, the actual implementation depends on the desired mocking behavior.
This is just one way to solve it, there are many others. I'm interested to hear what you find (in)convenient.
This question is a little old. Figured I'd provide an update since this is a pretty common situation.
Polymer CLI is the recommended approach for unit testing Polymer elements. The underlying library that it uses for testing is called web-component-tester (WCT). WCT has support for stub elements. Basically, if one of your tests relies on another element to return data, you can create a stub of that element that always returns consistent data.
JS in the unit test code for specifying the stub element:
setup(function() {
replace('paper-button').with('fake-paper-button');
});
Element to be tested:
<dom-module id='x-el'>
<template>
<paper-button id="pb">button</paper-button>
</template>
</dom-module>
At test runtime, the content template would be stamped out as:
<dom-module id='x-el'>
<template>
<fake-paper-button id="pb">button</fake-paper-button>
</template>
</dom-module>
https://www.polymer-project.org/1.0/docs/tools/tests#create-stub-elements
You can try registering it imperatively with js or extend every single element you are testing and override its properties or methods you want to mock.
i think that is just about it. It's like my google-map custom element, i import the google-map and change stuff around like so:
<polymer-element name="core-gmaps" attributes="lat long mapzoom markerlat markerlong markertitle" extends="google-map">
<template>
<style>
:host{
width: 100%;
}
#vivaMap {
display: block;
height: 100%;
width: 100%;
}
</style>
<google-map id="vivaMap" latitude="0" longitude="0" zoom="18">
<google-map-marker id="vivaMarker" title="" latitude="0" longitude=""></google-map-marker>
</google-map>
</template>
<script>
Polymer("core-gmaps",{
ready: function(){
var map = this.$.vivaMap;
map.latitude = Number(this.getAttribute('lat'));
map.longitude = Number(this.getAttribute('long'));
map.zoom = Number(this.getAttribute('mapzoom'));
var mapMarker = this.$.vivaMarker;
mapMarker.latitude = Number(this.getAttribute('markerlat'));
mapMarker.longitude = Number(this.getAttribute('markerlong'));
mapMarker.title = this.getAttribute('markertitle');
/*map.addEventListener('google-map-ready', function(e) {
console.log('Map loaded!');
});*/
}
});
</script>
</polymer-element>
I am still not sure if it was worth it professionally (i may end up not using it), but was totally worth it intellectually. learned some nice stuff. since i'm extending google-map it gets registered once and only once.
EDIT:
in my case i used the ready event because i couldn't manipulate the map per se without it being at least ready. but you can choose the event callback from the lifecycle methods. The list is here.
PS.:Yes, i didn't use data binding because i couldn't. The google map api was complaining about it being NaN so i had to cast it.

How to configure Ember CLI to use uncss

I have a hard time to configure Ember CLI to use uncss. The setup:
> ember new foobar
> cd foobar
> bower install --save-dev bootstrap
> ember generate route index
app/templates/index.hbs
<h1>Hello World!</h1>
Brocfile.js
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
var app = new EmberApp();
app.import('vendor/bootstrap/dist/css/bootstrap.css');
module.exports = app.toTree();
What do I have to do to use https://github.com/sindresorhus/broccoli-uncss? The assets part of http://iamstef.net/ember-cli/ says that it's easy but it doesn't describe how to actually do it.
It's not well documented in broccoli-uncss readme, but if you look at the
index.js and test.js, you would get the idea.
Basically you pass in a tree as the first parameter, and an options hash as the second parameter, And options hash should have an html option, telling where the index.html is. In your case I think what Oliver said is true. You could use the html in your dist folder. I am not sure how to integrate that with the ember-cli, but my guess is probably you need an ember-cli add-on, http://reefpoints.dockyard.com/2014/06/24/introducing_ember_cli_addons.html.
var uncss = require('broccoli-uncss');
var cssTree = uncss('dist`, {
// html file to uncss, or this could be a live link to the html
html: ['dist/index.html']
});
// you might somewhat merge this with ember-cli app tree here.
module.exports = cssTree;
Please correct me if I'm wrong...
I assume uncss won't work as expected in a "templating environment"!
Let's say you have an outer and an inner template. The outer looks like
<div class="outer">
{{outlet}}
</div>
and the inner template would look like
<h1>Text</h1>
In your css file you would maybe write something like
.outer h1 {
background: red;
}
As far as I know uncss would dismiss this css rule because uncss is not able to find it in either one of your templates.