Integration tests CRUD Ember.js - ember.js

I need to do integration tests for my Ember app, for example in the user template :
<div class="container">
<h1>{{model.firstName}} {{model.lastName}}</h1>
<p>Age: {{model.age}} years old</p>
<p>Job: {{model.job}}</p>
<img src="{{model.image}}" alt="img" id="image">
</div>
I have to test that the list of users is correctly displayed. Is it possible to do so ?
I have never done that and I'm kind of lost here. Would it be something like :
test('it renders all users', function(assert) {
this.set('users', [
{ firstName: 'Tubby'},
{ firstName: 'Spot'},
{ firstName: 'Chester'},
{ firstName: 'Frisky'}
]);
this.render(hbs`{{user users=users}}`);
assert.equal(this.$('.user').length, 4);
});
Even though I read many articles about the integration tests, I still don't understand if it can be used for something that is not a component.
What about redirection ? Let's just say that I have to write an integration test that verifies that the redirection is okay. Can I do that with integration tests ?
Thanks for your help.

It may be worth doing a quick review of the testing options:
Unit tests allow us to test small chunks of code. Things that are easy to test this way would be services, serializers or adapters.
Integration tests are primarily designed to let you test components and the way they work together and interact with users. Things often tested include events of different sorts (clicks, keystrokes, etc) and the way a component reacts to different types of data.
Acceptance tests are often used for testing the integrated whole of your app (pretending to be your user and browsing the site).
Often, checks for redirects would either be an acceptance test. You could also do unit tests (if you have complicated route logic that handles various scenarios that redirect). Testing redirects in an integration test would primarily focus around making sure clicking a button would attempt to redirect somewhere else.
Does that help?

I hope, The below tutorial will help you to understand the test case. The tutorial has examples for all testing(UNIT, Acceptance and Integration).
https://medium.com/#srajas02/ember-test-case-for-a-crud-application-with-mirage-d6d9836bfee2
Source Code: https://github.com/srajas0/ember-test-cases

Related

Is there a point in unit testing Mongoose schema

For purpose of demonstration assume that I have the following schema + model:
const UserSchema = mongoose.Schema({
userName: {
type: String,
required: true,
unique: true
}
});
const UserModel = mongoose.model("User", UserSchema);
I intend to have a large schema, so for easier maintenance I have it defined in user.schema.js, whereas the corresponding user model is in a separate file.
I covered the model with unit tests and began contemplating doing the same for the schema module, except... I am not sure if there is a point?
I have seen people test their models/schemas using an actual test database connection, but that is not a unit test IMO, it resembles an integration test more, and that is a different concept. For a unit test of a schema only I don't care if MongoDB itself works correctly.
The Internet (including SO) has also revealed code, which tests Mongoose's validation. This is closer to what I wanted to do as the basic idea is to check whether all expected props and restrictions are in the schema. It would look like this:
it('should be invalid if username is empty', function(done) {
new UserModel().validate(function(err) {
expect(err.errors.name).to.exist;
done();
});
});
If testing with a live DB one could change .validate to .save too.
Then it dawned upon me that I would be doing two things here:
Testing the behaviour of Mongoose, which I also don't care/intend/want to do.
Essentially duplicating my schema. If I later decide to change anything in it, I would have to change the unit test too.
This seems like unit testing a configuration object, and that is pointless, aside from maybe making sure that I wrote my regexes correctly and stuff like that.
Questions
I have thus decided not to test the schema at all. Does that make sense or am I missing something?
As a side question, do you believe there is a point in writing tests with a DB connection? This would test my schema + mongoose + mongo and somehow I find it redundant.

Ember Unit Testing Templates

I'm in the early stages of using Ember in a project. So far I'm very excited about the possibilities it opens up!
We're writing integration tests as described in their docs. We also plan to do unit testing of various things at a later stage when required (components, controllers, views etc).
Right now, however, we just have a basic template to which a model is bound. For illustrative purposes it could simply be:
<h1>{{title}}</h1>
We're precompiling our templates on the server: they're available in the Ember.TEMPLATES collection.
We'd like to unit test just this template with a model (created in the test) bound to it. My thinking is that we should just be able to load the app on a page, specify a page element into which the template should be rendered, create a dummy model, bind it 'somehow' to the template, render the template and then do some jQuery assertions. Sounds straight-forward, but I can't seem to find out how to do this in an easy way.
I've already looked at this post and posts like this, but they either seem to be out of date or deal with views, which I don't think we have a need for with such a simple template.
Can anyone point me in the right direction? Am I looking at this problem the wrong way? We're using qunit and ember-qunit combi as recommended in the Ember docs, in case that's of importance.
You can always create a view on the fly and attach a controller and your template to it, then attach it to the page and test that the bindings are working.
var controller = Em.ObjectController.create({
model: { title: 'hello'}
});
var fooView = Em.View.create({
container: App.__container__,
templateName: 'foo',
controller: controller
});
// start up the run loop and inject template into the page
Em.run(function(){
fooView.appendTo('#foo');
});
equal(find("h1").length, 1, "h1 is injected");
equal(find("h1").html(), 'hello', "text says hello");
fooView.remove(); // cleanup
http://emberjs.jsbin.com/wipo/45/edit

good examples of testing ember with rest adapter in quint or mocha

I have been trying to test my ember application for 2 days with no success. There are examples out there that use fixtures but I was wondering if you might have an example of test scripts where RESTAdapter was used. I have tried using Fixtures for testing as you can see in the fiddle here : http://jsfiddle.net/deewen/u68Mx/1/, but that is also not working for me(sorry I couldn't find proper expect.js file).
it("Check analyticsRuns controller", function () {
//var controller = AS.__container__.lookup('controller:analyticsRunsIndex');
//the returns null too even though I have that controller
visit('/analytics')
.then(function() {
expect(find('*')).to.not.be(undefined);
});
});
Any suggestions for resource or read that could guide me on this would be highly appreciated. Thanks.
In general you don't want your test to hit a live API endpoint because at that point you're not only testing your application code, you're also testing both the functionality of the API and the state of any data that may (or may not) already be stored in the API service.
The Ember Data tests setup fake AJAX responses, much like you'd do with something like webmock on the server side. Something like that is probably the way to go.
https://github.com/emberjs/data/blob/master/packages/ember-data/tests/integration/adapter/rest_adapter_test.js#L34-L55

Test driven development - when/what to test?

I am trying to get started with TDD but right away I am unsure of when and what I should be testing. The first two tasks in a new project I'm working on are as follows.
1) Receive some JSON formatted data on a REST endpoint and save it in the database. Say the data was several car records -
{
"cars": [{
"make": "ford",
"color": "blue",
"year": "2010",
"for_sale": true
}, {
"make": "bmw",
"color": "black",
"year": "2011",
"for_sale": false
}
] }
So that data arrives at a REST endpoint and I need to save it in the database. Do I need a test for this task and if so what should it look like?
2) Retrieve some records from the database and display them in a view/webpage (i.e. using some templating system). Say the records are the car records above and they should be displayed as follows -
<ul id="cars">
<li id="car-1">
<div><span>Make:</span><span>Ford</span>
</div>
<div><span>Color:</span><span>blue</span>
</div>
<div><span>Year:</span><span>2010</span>
</div>
<div><span>For sale:</span><span>Yes</span>
</div>
</li>
<li id="car-2">
<div><span>Make:</span><span>BMW</span>
</div>
<div><span>Color:</span><span>black</span>
</div>
<div><span>Year:</span><span>2011</span>
</div>
<div><span>For sale:</span><span>No</span>
</div>
</li>
</ul>
So do I need a test for this task and if so what should it look like?
What language, platforms etc are you using? Perhaps we can find some examples for you.
TDD is tricky at first, and a task like this (with Database and web parts) requires testing at several levels.
First divide the task up into single-responsibilities (which probably map to classes) that can be unit tested. For example, a class that takes JSON input, and hydrates an object with properties on it, TDD that class. Database layers are hard to unit test, we normal use the Repository pattern which we then mock when testing other classes.
DB unit testing is hard, so consider an "acceptance" or "integration" test around the database. That might be a test that connects to a real test database, puts in some test data, pulls it out again, and verifies that it looks right. In theory, you then don't even care what database it is, as long as the stuff you store comes out again, you know it's working.
HTML / web testing it also best done at a high level using tools such as selenium webdriver, which allows you to write test code that fires up a real browser, interacts with your page, and asserts that the content/behaviour is as expected.
This stuff is really good learnt by pair programming with someone who already knows it, or perhaps by attending a class or training course. There are also lots of books blogs and tutorials, which let you learn in a sandbox, which is simpler than trying to learn by yourself on a real project, where the pressure to get stuff done is in conflict with learning.
Edit: Java and Play framework.
OK, I don't know the play framework specifically, but from a quick look it probably does the JSON parsing for you if you set it up right, which reduces the json parse function to boilerplate code. There's not a huge amount of value in TDD here, but you can if you want. Similarly, there's an active-record style db layer? So there's not a lot of value in testing code your library has provided (and dbs are hard/impossible/pointless* to unit test) .
Edit:Edit - this turns out to be icky, Apparently Play uses static controller methods which makes it hard to unit test (because you can't inject dependencies - which makes mocking difficult). I'm afraid without doing hours of research I can't help with the specifics, but integration tests are probably the way to go here, which test several of your units of code together, including the DB.
So in summary:
Don't sweat TDD on the boilerplate. Keep boilerplate isolated and thing (ie controllers ONLY do web stuff, then hand over to other classes. Repositories only save and retrieve objects, not rules/decisions/manipulations.
When you start adding more business logic to the guts of your app - keep it isolated in business classes (ie - away from the web or db boilerplate) that you can unit test easily. Definitely TDD this stuff.
Try integration tests across your app to test the DB. Have a real test DB behind your app, use the app to save something, retrieve it, and then assert it's correct.
use something like Selenium to test the web pages.
*delete according to your testing beliefs.

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.