I have the following standard react-admin structure set–up and everything works as expected, the resource gets the data from the endpoints for GET_LIST and GET_ONE the issue I have is I want to test the CandidateView component and I do not know how to pass it some mocked data to check when rendered it will contain all the data expected.
<Admin
title="Admin"
dashboard={Home}
dataProvider={restProvider}
history={history}
loginPage={Login}
menu={Menu}
>
<Resource
name="candidates"
list={Candidates}
icon={UserIcon}
edit={CandidateEdit}
show={CandidateView}
/>
</Admin>
Do I have to mount the Resource to be able to test this or is there a better way in which I can just mount and test the subcomponents that I'm interested in?
To be honest, React Admin controllers are designed to be easy to use and hack with, not easy to test.
Assuming that you are using a simple show view like this one:
export const CandidateView = props => (
<Show {...props}>
<SimpleShowLayout>
<TextField source="title" />
<TextField source="position" />
<RichTextField source="body" />
<DateField label="Registration date" source="created_at" />
</SimpleShowLayout>
</Show>
);
Indeed, you can read the source code, find all the HOCs, inject all the required props, mounting the view and test the output. It's painful, but doable.
But if your only goal is just to test that this view has the correct fields that are title, position, body and created_at, it isn't an efficient way to do it.
We see the React Admin resource declaration as a simple configuration. (you won't test XML files)
On our apps, we use end-to-end tests to check that all views are well configured and have the right components and behaviors.
You can find an example of E2E tests with cypress or selenium for that page on React Admin itself.
Take a look in cypress/integration folder to see all the tests we run.
Related
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
I am using angular 6.1.6 and really new to Karma. When I run ng test,
the result shows some elements (please see screenshot here). Can I hide them/remove from my testing result?
Thank you.
I got another answer.
Putting this in the beforeEach function works well
fixture.debugElement.nativeElement.style.visibility = "hidden";
and it would hide the flashing component when testing.
It looks like your test is adding things directly to the dom, which is non-standard (though there are some instances where this is a good idea). In general, your tests should not attach any dom to the document object (eg- by calling document.querySelector('#foo').appendChild(...). If you create dom elements, you should avoid attaching them to the document.
If you do attach dom elements to the document, the simplest way to remove them is in an afterEach block in your describe spec, like this:
afterEach(() => document.querySelector('#my-element').remove());
I am trying to develop a Laravel composer package and run unit tests from within it. After spending the last couple of days reading various outdated and contradictory guides and blogposts, I am completely confused as to how to go about this.
Here's what I know so far:
I shouldn't run tests from the main Laravel installation. Tests should all be contained within the package. I'll admit this has a certain logic to it.
There's something called Orchestra Testbench. If you're developing a Laravel package then apparently you should use this.
There's also something called Laravel Dusk, which is included in Laravel 5.4.
I can get Orchestra Test Bench working with some basic tests from the examples given, but I don't really understand what's going on and the documentation explains almost nothing. When it comes to testing my application's routes, I can't get anything to work.
I don't understand if Orchestra and Dusk can play together, or if I have to choose between them. If so, which one should I use?
And if it's Laravel Dusk I should be using, then how do I run it from within my package directory?
I agree with:
I shouldn't run tests from the main Laravel installation. Tests should all be contained within the package
To avoid installing Laravel in your application and bootstraping it by hand to test your package, you can use Orchestral Testbench.
The docs of Orchestral are pretty good today, but I will give anyway a short example how to use it, if you want to make unit tests on some Eloquent models.
First, make sure that your package has a ServiceProvider class which points to your migration files as described in the docs.
Then, require the orchestral/testbench package into your package and create a file in tests/TestCase.php.
The file TestCase should do the following:
Extend Orchestra TestCase
Point to your Service-Provider with getPackageProviders
Setup a SQLite database in memory with getEnvironmentSetUp
Run migrate to create you tables in setUp()
Here is an example:
<?php
namespace MyVendorName\MyPackageName\Tests;
use MyVendorName\MyPackageName\MyServiceProvider;
class TestCase extends \Orchestra\Testbench\TestCase
{
public function setUp(): void
{
parent::setUp();
$this->artisan('migrate', ['--database' => 'testbench'])->run();
}
/**
* add the package provider
*
* #param $app
* #return array
*/
protected function getPackageProviders($app)
{
return [MyServiceProvider::class];
}
/**
* Define environment setup.
*
* #param \Illuminate\Foundation\Application $app
* #return void
*/
protected function getEnvironmentSetUp($app)
{
// Setup default database to use sqlite :memory:
$app['config']->set('database.default', 'testbench');
$app['config']->set('database.connections.testbench', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
}
}
And to answer your second question: Laravel Dusk works well with Orchestral Testbench. Similar as above where you needed to mock up a database to test your Eloquent package models, you have to mock up routes & views with Orchestral to make the Browser tests with Laravel Dusk.
For more details, check out my blog post.
Here is what I do when developing a package:
1) Create a folder named src/tests.
2) Inside this folder I follow the "normal" structure:
A Unit folder for unit tests.
A Feature folder.
A Browser folder for running tests with Laravel Dusk (for the end-to-end tests).
Note: Dusk allows you to test your application as a real user would do clicking links, filling forms, etc. It is really cool to test an application user interface (even if it uses JavaScript). So, if your package does not include any interface you may not need Dusk.
3) All the tests use the base testing suite of Laravel, so you need a full Laravel installation with Dusk included (Dusk only needed if you are using browser tests).
So for the Unit and Feature tests I extended \Tests\TestCase.
Browser tests extend \Tests\DuskTestCase.
4) Now run your tests using the path to your tests:
phpunit /path/to/packages/pascall/icms
or, for Dusk:
php artisan dusk /path/to/packages/pascall/icms
(or you can cd /path/to/packages/pascall/icms and then run phpunit.
I have never used Orchestra because my team finds this option more straightforward and easier so I can't help you with that.
Drawbacks:
Dusk test failures will appear in the Default Laravel Dusk screenshot folder (for us this is fine so we have not spent time investingating this).
I did all of the things that others said but my problem didn't been solved unless I change <testsuites> in phpunit.xml of Laravel's root :
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">packages\YourVendorName\YourPackageName</directory>
</testsuite>
</testsuites>
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.
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.