CanJS: Unit testing of different parts - unit-testing

I have one question. I've started to use CanJS just recently and trying to create unit tests (funcunit / jasmine ) that will work in maven build with TeamCity (headless).
It was relatively easy to test Model, because it doesn't rely on any view and you can create instance and test functionality.
But it not so clear for me how to test Components and other parts of CanJS. Just to clarify i don't need E2E tests with user interaction, what i'm trying to achieve is just have some data provided by Can.fixtures and then just test that my functions works fine by calling them in tests.

Controller tests benefit from the addition of jasmine-fixture to your Jasmine test bed. You can affix() the appropriate DOM elements and instantiate the controller in beforeEach() before adding spies to the instance or the controller prototype, then fire events or directly call functions requiring some DOM tree to be available.
For Components, there's one more step involved. Because of the way Components are instantiated, either you have to use can.view() to create and attach their custom elements to the DOM (and clean it up in afterEach()), or you have to use can.view.callbacks.tagHandler(el, tag_name) to manually instantiate the Component for an element already in the DOM.
To be clear, this makes things easier when your controller/component functions are slurping data from the DOM, as in event handlers. It also works to just call the functions directly on the prototype and make spy objects for this.scope and this.options

Related

Mock a repository while testing an api controller

Im trying to get familiar with using MOQ and mocking in general. So I want to test an api controller which uses an assembly which serves as a repository for getting/updating data etc.
eg a structure like this.
HomeController
Index
Repository.GetSomeData (returns JSON object)
This repository class has an interface, and that is what is injected via the .net core startup class. The method in this case, GetSomeData does a number of steps via calls to the Db, as well as reading a file from the file system, parsing it and moving it off to another folder.
Question: How can a "mocked" Repository work without doing the things that the "real" object does? All the examples I see are simple addition, returning strings etc.
When you mock something like your repository, you going to stub out methods on the repository to return some canned result. Calls to those methods on the repository mock, then, bypass the real methods and instead just do what you've stubbed.
Essentially, you need to first identity what methods will be utilized. Then, you should determined appropriate responses those methods should return based on the particular scenario you're attempting to unit test. Then, you create the mock and add stubs for those methods with those responses.
The whole point of mocking is to remove variables, so you're intentionally trying to get to the "happy path": the set of internal responses that put the action in the state you need it to be in for specific test you're conducting.

Unit Testing basic Controllers

I have a number of simple controller classes that use Doctrine's entity manager to retrieve data and pass it to a view.
public function indexAction() {
$pages = $this->em->getRepository('Model_Page')->findAll();
$this->view->pages = $pages;
}
What exactly should we be testing here?
I could test routing on the action to ensure that's configured properly
I could potentially test that the appropriate view variables are being set, but this is cumbersome
The findAll() method should probably be in a repository layer which can be tested using mock data, but then this constitutes a different type of test and brings us back to the question of
What should we be testing as part of controller tests?
Controller holds core logic for your application. Though simple "index" controller actions don't have any specific functions, those that verify/actively use data and generate viewmodels have pretty much the most functionality of the system.
For example, consider login form. Whenever the login data is posted, controller should validate login/password and return: 1) to index page whenever logins are good. Show welcome,{user} text. 2) to the login page saying that login is not found in db. 3) to the login page saying that password is not found in db.
These three types of outputs make perfect test cases. You should validate that correct viewmodels/views are being sent back to the client with the appropriate actions.
You shouldn't look at a controller like at something mysterious. It's just another code piece, and it's tested as any other code - any complicated logic that gives business-value to the user should be tested.
Also, I'd recommend using acceptance testing with framework like Cucumber to generate meaningful test cases.
Probably the controller is the hardest thing to test, as it has many dependencies. In theory you should test it in full isolation, but as you already seen - it has no sense.
Probably you should start with functional or acceptance test. It tests your controller action in a whole. I agree with previous answer, that you should try acceptance testing tools. But Cucumber is for Ruby, for PHP you can try using Codeception. It makes tests simple and meaningful.
Also on a Codeception page there is an article on how to test sample controllers.

Correct way to metaprogram in grails so its available in unit tests

I can add a method to the java Integer type in Groovy with the lines:
ExpandoMetaClass.EnableGlobally()
Integer.metaClass.gimmeAP = {->return 'p'}
I don't know why I'd need that, but it gets the point across. Now I can make calls to Integers and get back a 'p'. Now lets say I want this in a grails app so I can make calls in the domain objects. The specific problem I'm having is that when I put those metaprogramming lines in the bootstrap all the metaprogramming isn't available in the unit tests, so my unit tests are failing with errors like "No method gimmeAP for java.lang.Integer" or something like that.
How do I either include the metaprogramming better, or execute that part of the bootstrap so I can use my tricked out syntax in unit tests?
I have seen this question: Grails - Making Methods Globally Available and Metaclass Programming and it seems my line ExpandoMetaClass.EnableGlobally() may fix his problem, but am I using it right?
Bootstrap isn't executed for unit tests. I would personally prefer to create a mockFoo method that does the above meta programming, and Then I will call the mockFoo from the test setup.
Also look at the GrailsUnitTestCase.registerMetaClass. Register metaclass before you add mock methods, so that they don't leak in other tests.
registerMetaClass(SecurityUtils)
SecurityUtils.metaClass.'static'.getSubject = { ->
return [logout: { return true } ] as Subject
}
I know you want to make your dynamic methods available to all unit tests, but there's nothing such as bootstrap for unit tests. So you have to do it in each test.
You can create a MockHelper with a static method, and call it from test setUp.

Testing Mongoose Node.JS app

I'm trying to write unit tests for parts of my Node app. I'm using Mongoose for my ORM.
I've searched a bunch for how to do testing with Mongoose and Node but not come with anything. The solutions/frameworks all seem to be full-stack or make no mention of mocking stuff.
Is there a way I can mock my Mongoose DB so I can return static data in my tests? I'd rather not have to set up a test DB and fill it with data for every unit test.
Has anyone else encountered this?
I too went looking for answers, and ended up here. This is what I did:
I started off using mockery to mock out the module that my models were in. An then creating my own mock module with each model hanging off it as a property. These properties wrapped the real models (so that child properties exist for the code under test). And then I override the methods I want to manipulate for the test like save. This had the advantage of mockery being able to undo the mocking.
but...
I don't really care enough about undoing the mocking to write wrapper properties for every model. So now I just require my module and override the functions I want to manipulate. I will probably run tests in separate processes if it becomes an issue.
In the arrange part of my tests:
// mock out database saves
var db = require("../../schema");
db.Model1.prototype.save = function(callback) {
console.log("in the mock");
callback();
};
db.Model2.prototype.save = function(callback) {
console.log("in the mock");
callback("mock staged an error for testing purposes");
};
I solved this by structuring my code a little. I'm keeping all my mongoose-related stuff in separate classes with APIs like "save", "find", "delete" and no other class does direct access to the database. Then I simply mock those in tests that rely on data.
I did something similar with the actual objects that are returned. For every model I have in mongoose, I have a corresponding class that wraps it and provides access-methods to fields. Those are also easily mocked.
Also worth mentioning:
mockgoose - In-memory DB that mocks Mongoose, for testing purposes.
monckoose - Similar, but takes a different approach (Implements a fake driver). Monckoose seems to be unpublished as of March 2015.

mocking the return value of domainInstance.validate()

I am writing a spock unit test that tests a controller method.
The controller action under test instantiates a new domain instance object and
calls validate on it before it saves.
Is there anyway of mocking the call to domainInstance.validate() so I
can make it return whatever I want? Or do I have to hide this
instanciation and saving behind a service method to achieve this?
I do this this way, because within the context of a unit test for a
controller, the constraints of a domain object should not be involved.
I test those elsewhere (in the MyDomainClassTests, obviously). If I
wanted to take those into into account my test would be an integration
test.
If you didn't place the validate on the domain instance itself, but rather in a service,
you could let your controller take a Service in its constructor (or rather an interface of a service). Let that service handle the validation.
Now for your unittest of that controller, you would pass in a Mock of that interface(service) to the controller and configure the mock to return whatever you want.
For .net i can recommend Moq (http://code.google.com/p/moq/)
After a while I have come to the conclusion that what I wanted is rather tricky. If you're in a scenario where you don't have to use mockDomain(), you could add a groovy metaclass method and it's implementation (return true or false, whichever you want)
If you do need mockDomain() because you need to mock pre-existing instances you are out of options, at least for now because mockDomain() and fiddling with metaclass methods that mockDomain actually provides will not mix.