Unit testing a controller that invokes a method that checks the DOM for a property - unit-testing

I am writing a unit test for a controller where somewhere in the workflow checks the DOM for a specific property. Currently I am just mocking the method via
spyOn(controller, 'methodChecksDom').return('value that I want').
Works fine but how do I make the test pass without mocking that method. I've tried using $document and actually inserting dom via
$document.find('body').append('<div>...</div>')
but I get the following error in my test:
Error: Dirty test! DOM residue found in document body: ...
at Error (native)
What is the proper way of doing this. Testing the method without mocking it. Many Thanks!

If you're dead set on testing the DOM directly here, you need to clean up the inserted element after the test. That's why you're getting an error--you're not cleaning up the thing you inserted via $document.
That being said, you really should not be even so much as reading the DOM inside of a controller.

You should do any DOM manipulation or adding of behaviors by using a custom directive.
http://docs.angularjs.org/guide/directive
angular.module("myApp",[]).directive("mydirective",function(){
return {
link: function(scope,iElem,iAttrs) {
//Do stuff per instance here
}
}
})

Related

Mocking PDFtron webviewer with jest in react application

Hi I am new to unit testing and I am trying to mock the 'annotationManager' of the PDFtron webviewer
I am using this below code in my test file
jest.mock('#pdftron/webviewer', () =>({
annotationManager: {
getAnnotationsList: jest.fn().mockReturnValue([]),
deleteAnnotations: jest.fn()
},
}));
In the code, I'm getting the list of annotations using 'getAnnotationsList' function and deleting it using 'deleteAnnotations' function.
In the log of the unit tests, I'm getting this following error
'cannot read the properties of undefined (reading 'getAnnotationsList')
Is this the correct way to doing things or am I missing something?
are you able to share an example of a test you are writing where you need to mock the annotation manager? Depending on how you are using the WebViewer package, mocking the annotation manager can be different. If you prefer to reach out to Apryse directly you can also reach out to them via their support form

Polymer 1.x unit testing spy not getting called

I have a piece of code which is doing some DOM manipulation calling functions like appendChild and RemoveChild.
so, say my component has a div tag with id property
<div id="header"></div>
Inside my component in one of the functions I am getting hold of the mentioned tag and appending something
this.$.header.appendChild('<div>Hello</div>')
In my unit test I create test fixture with the responsible component and then inside I create a spy like
var testSpy = sinon.spy(Polymer.dom($el.$.header), 'appendChild')
this is done inside my setup. And then inside my it block I check for the spy to be called. But it not getting called. Though the appendChild is being called and I could see the dom correctly as well. But in the expect it is not working. Any help?
So, I was able to figure it out on my own. The only different thing which I did was the way I was getting hold of my DOM while creating the spy:
var testSpy = sinon.spy($el.querySelector('#header'), 'appendChild')
After that my spy started to be called.

How to check props of a DOM node in an unit test in React 0.14?

After upgrading React from 0.13 to v0.14.0-beta3, I got a lot of warnings like this in my unit tests:
Warning: ReactDOMComponent: Do not access .props of a DOM node; instead, recreate the props as `render` did originally or read the DOM properties/attributes directly from this node (e.g., this.refs.box.className). This DOM node was rendered by `Button`.
They are caused by my unit tests, for example:
it('should render to a <a> when href is given', function () {
var button = TestUtils.renderIntoDocument(<Button className="amazon" href="#">Hello</Button>);
expect(TestUtils.scryRenderedDOMComponentsWithTag(button, 'button').length).toBe(0);
expect(TestUtils.scryRenderedDOMComponentsWithTag(button, 'a').length).toBe(1);
expect(TestUtils.scryRenderedDOMComponentsWithTag(button, 'a')[0].props.href).toBe('#');
expect(TestUtils.scryRenderedDOMComponentsWithTag(button, 'a')[0].props.className).toBe('amazon Button');
});
How do I fix this? Is there any recommended practice for testing DOM elements like this?
In the debugger I discovered that these elements (like, in my case, TestUtils.scryRenderedDOMComponentsWithTag(button, 'a')[0]) are in fact DOM elements with just some React properties added (like props and state).
So now, with this knowledge, I can write my assertions based on DOM attributes and properties, like:
expect(b.getAttribute('href')).toEqual('#');
To fix the warning just call a prop directly.
For example:
warning code:
this.refs.input.props.name
fixed code:
this.refs.input.name

Errors from debounced function calls in testing ember application

I'm testing an relatively large Ember application (http://wheelmap.org/map) with QUnit and having problems with debounced calls e.g. changing the url to have a permalink of a map view inside the app or doing a manual AJAX request while testing.
I followed the documentation at http://emberjs.com/guides/testing/integration/
Now when I reset the application state by calling App.reset() in the module setup it resets all bindings, etc. to variables and dependant controllers.
module('Map', {
setup: function() {
App.reset();
}
});
This seems to be good to have a clean working environment, but leads to errors where variables are accessiable by Ember.set and Ember.get e.g. this.get('controllers.toolbar'):
Cannot call method 'set' of null
So the first test allways runs great, but further tests break because of debounced function calls from the first test. So what I think I have to do is stop this debounced calls somehow.
Other options would be checking if all needed variables are set in this function calls. But this seems to be cumbersome when adding conditions only for testing.
What do you think?
Thank you in advance!
I found the answer by searching through the RunLoop source files:
Ember.run.cancelTimers()
It's not part of the documentation. Maybe a problem of poor documentation or not beeing part of the public API.
Now I just call it in the module test teardown function:
module('Map', {
setup: function() {
// ...
},
teardown: function() {
Ember.run.cancelTimers()
}
});
We ran into a similar problem and decided to disable debounce during testing.
You can check if in testing mode using if(Ember.testing){...}.

MVCContrib Testing Route with Areas

I am using MVC 2 with Areas. To test routing, I am using MvcContrib.
This is the testing code:
[Test]
public void Home()
{
MvcApplication.RegisterRoutes(RouteTable.Routes);
"~/".ShouldMapTo<HomeController>(x => x.Login("Nps"));
}
I am not sure how to call routing definition that are stored in Areas.
Calling AreaRegistration.RegisterAllAreas() is not an option as it gives an exception.
Thanks
Revin
This is the way I do it which works for me
[Test]
public void VerifyRouteMapFor_Test_Area_TestController()
{
RouteTable.Routes.Clear();
var testAreaRegistration = new testAreaRegistration();
testAreaRegistration.RegisterArea(new AreaRegistrationContext(testAreaRegistration.AreaName, RouteTable.Routes));
"~/test/index".ShouldMapTo<testController>(x => x.Index());
}
Rather than calling RegisterAllAreas, you should call the AreaRegistration for that area you are testing. The RegisterAllAreas scans all the loaded assemblies and as a result does too much for a test. I would manually setup the test. If it still throughs and exception post it here or to the mvccontrib mailing list. I am sure that there are some cases where the TestHelper needs to be updated to support areas better. We have not added any specific area support to the test helpers yet.
For a unit test, perhaps it's best to just do the one area. But for an integration test, you'd want to test all the routes in the context, imo.