How to create automated test case in laravel - laravel

Is there any way to create automated test case in laravel. It means when I will run the test case it will open browser automatically, check the validation, submit the form etc.

Yes, it is quite possible. From the documentation:
Laravel provides several methods for testing forms. The type, select,
check, attach, and press methods allow you to interact with all of
your form's inputs.
A sample test case would look something like:
public function testNewUserRegistration()
{
$this->visit('/register')
->type('Taylor', 'name')
->check('terms')
->press('Register')
->seePageIs('/dashboard');
}

Related

How should you structure CRUD cypress tests?

I'm working on a React app and our team is writing Cypress tests for it. We want to test basic CRUD functionality, so we have created three tests:
CREATE user
UPDATE user
DELETE user
The CREATE test uses a fixture to define the new user.
The UPDATE and DELETE tests reference that same fixture and update and delete the user that was created in the previous test. This means the UPDATE and DELETE tests are dependent on the CREATE test. Is this ok?
Based on what I'm reading, it sounds like each Cypress test should be able to run independently and I can see that's not the case here.
However, what is the best way to do that?
I don't think it makes sense to copy and paste the same 10-20 lines of code from the CREATE test and duplicate them in both the UPDATE and DELETE tests. Is there a way we can abstract the CREATE test and include it in the UPDATE and DELETE tests?
Or should we just combine all three tests into a single "CRUD user" test?
Based on what I'm reading, it sounds like each Cypress test should be able to run independently.
Ideally, yes. There are several reasons for that:
in theory, if one test fails, the other ones can still pass; but if your test that creates some entity (user in your case) fails, the other ones will fail for sure, but not because of what they focus on
you don't really have a way to ensure the tests will be executed in the same order; although in Cypress I think it's based on alphabetical order, but this might not apply with other tools or even with Cypress in the future; or you decide to add some test somewhere which changes the order of tests and all of a sudden some tests will fail and you won't instantly know why
I don't think it makes sense to copy and paste the same 10-20 lines of code from the CREATE test and duplicate them in both the UPDATE and DELETE tests. Is there a way we can abstract the CREATE test and include it in the UPDATE and DELETE tests?
Cypress offers for example commands, so your final test code can look like this:
it('CREATE user', () => {
cy
.fixture('user')
.then(user => {
cy
.createUser(user)
// whatever checks you need to perform here
.its('response.statusCode')
.should('eq', 201);
});
});
then if your 10-20 lines of code are hidden behind cy.createUser(), you can easily reuse that in other tests:
it('DELETE user', () => {
cy
.fixture('anotherUser')
.then(anotherUser => {
cy
.createUser(anotherUser)
.then(response => {
cy
.deleteUser(response.body.id)
// whatever checks you need to perform
.its('response.statusCode')
.should('eq', 204);
});
});
});
I think such code reads quite easily and the tests are short as well, so it is easily maintained if need be.

How to feature test more complicated cases on Laravel using PHPUnit

I'm using Laravel for my project and I'm new to unit/feature testing so I was wondering what is the best way to approach more complicated feature cases when writing tests?
Let's take this test example:
// tests/Feature/UserConnectionsTest.php
public function testSucceedIfConnectAuthorised()
{
$connection = factory(Connection::class)->make([
'sender_id' => 1,
'receiver_id' => 2,
'accepted' => false,
'connection_id' => 5,
]);
$user = factory(User::class)->make([
'id' => 1,
]);
$response = $this->actingAs($user)->post(
'/app/connection-request/accept',
[
'accept' => true,
'request_id' => $connection->id,
]
);
$response->assertLocation('/')->assertStatus(200);
}
So we've got this situation where we have some connection system between two users. There is a Connection entry in the DB created by one of the users. Now to make it a successful connection the second user has to approve it. The problem is within the UserController accepting this through connectionRequest:
// app/Http/Controllers/Frontend/UserController.php
public function connectionRequest(Request $request)
{
// we check if the user isn't trying to accept the connection
// that he initiated himself
$connection = $this->repository->GetConnectionById($request->get('request_id'));
$receiver_id = $connection->receiver_id;
$current_user_id = auth()->user()->id;
if ($receiver_id !== $current_user_id) {
abort(403);
}
[...]
}
// app/Http/Repositories/Frontend/UserRepository.php
public function GetConnectionById($id)
{
return Connection::where('id', $id)->first();
}
So we've got this fake (factory created) connection in the test function and then we unfortunately are using its fake id to run a check within the real DB among real connections, which is not what we want :(
Researching I found an idea of creating interfaces so then we can provide a different method bodies depending if we're testing or not. Like here for GetConnectionById() making it easy to fake answers to for the testing case. And that seems OK, but:
for one it looks like a kind of overhead, besides writing tests I have to make the "real" code more complicated itself for the sole purpose of testing.
and second thing, I read all that Laravel documentation has to say about testing, and there is no one place where they mention using of interfaces, so that makes me wonder too if that's the only way and the best way of solving this problem.
I will try to help you, when someone start with testing it is not easy at all, specially if you don't have a strong framework (or even a framework at all).
So, let me try help you:
It is really important to differentiate Unit testing vs Feature testing. You are correctly using Feature test, because you want to test business logic instead of a class directly.
When you test, my personal recommendation is always create a second DB to only use with tests. It must be completely empty all the time.
So, for you to achieve this, you have to define the correct environment variables in phpunit.xml, so you don't have to do magic for this to work when you only run tests.
Also, use RefreshDatabase trait. So, each time you run a test, it is going to delete everything, migrate your tables again and run the test.
You should always create what you need to have as mandatory for your test to run. For example, if you are testing if a user can cancel an order he/she created, you only need to have a product, a user and an invoice associated with the product and user. You do not need to have notifications created or anything not related to this. You must have what you expect to have in the real case scenario, but nothing extra, so you can truly test that it fully works with the minimum stuff.
You can run seeders if your setup is "big", so you should be using setup method.
Remember to NEVER mock core code, like request or controllers or anything similar. If you are mocking any of these, you are doing something wrong. (You will learn this with experience, once you truly know how to test).
When you write tests names, remember to never use if and must and similar wording, instead use when and should. For example, your test testSucceedIfConnectAuthorised should be named testShouldSucceedWhenConnectAuthorised.
This tip is super personal: do not use RepositoryPattern in Laravel, it is an anti-pattern. It is not the worst thing to use, but I recommend having a Service class (do not confuse with a Service Provider, the class I mean is a normal class, it is still called Service) to achieve what you want. But still, you can google about this and Laravel and you will see everyone discourages this pattern in Laravel.
One last tip, Connection::where('id', $id)->first() is exactly the same as Connection::find($id).
I forgot to add that, you should always hardcode your URLs (like you did in your test) because if you rely on route('url.name') and the name matches but the real URL is /api/asdasdasd, you will never test that the URL is the one you want. So congrats there ! A lot of people do not do this and that is wrong.
So, to help you in your case, I will assume you have a clear database (database without tables, RefreshDatabase trait will handle this for you).
I would have your first test as this:
public function testShouldSucceedWhenConnectAuthorised()
{
/**
* I have no idea how your relations are, but I hope
* you get the main idea with this. Just create what
* you should expect to have when you have this
* test case
*/
$connection = factory(Connection::class)->create([
'sender_id' => factory(Sender::class)->create()->id,
'receiver_id' => factory(Reciever::class)->create()->id,
'accepted' => false,
'connection_id' => factory(Connection::class)->create()->id,
]);
$response = $this->actingAs(factory(User::class)->create())
->post(
'/app/connection-request/accept',
[
'accept' => true,
'request_id' => $connection->id
]
);
$response->assertLocation('/')
->assertOk();
}
Then, you should not change anything except phpunit.xml environment variables pointing to your testing DB (locally) and it should work without you changing anything in your code.

Accessing dynamic links in the format of domain.com/<dynamic_page_name> in CodeIgniter

I am using code Igniter for my PHP project. I want to give provision in my site such that users can create new pages of their own, and access them directly from domain.com/their_page_name.
But, my developers have raised a concern that, 1000's of dynamic links that are presented in the format of domain.com/ is "not good for site's performance". For some 10-15 pages, it is fine. But, beyond that, it would effect the site's performance.
So, they proposed that the URL format should be like www.domain.com/something/page_name (here, 'something' is the controller name, as they mentioned it)
But, I really can't sacrifice my framework nor my requirement.
Is there any way that I can achieve the format of "www.domain.com/page_name" without effecting the site's performance?
Thanks in advance.
No issues on
Www.domain.com\userpagename.
It's not a framework issues. Codeigniter support this type of URL.you can create n no of URL.
Performance will matter how you are handling that particular controller or that particular function.
If may be 10 may be 100 ,work around same way.
You just have to put route accordingly.
$route[default_controller]=userurl;
$route[userurl/(:any)]=userurl yourfunction/$1`;
What it seems you need is dynamic controller, which can be done using Codeigniter's build in function _remap().
A code example is:
public function _remap($method){
if($method != null){
$this->yourFunction($method);
} else {
// handle the error as you like
}
}
public function yourFunction($key){
// your code logic here
}
All this code block goes inside your controller.
Edit: the performance is exactlu the same as going with domain.com/controller/method. What it matters, as stated above, is how you handle the data.

What is the best place to put onEnter, onExit callback functionality?

I am creating my first project that uses ui-router.
My project has about 10 views, each with their own controller and state. I am trying to modularise/encapsulate/decouple as best as possible but I am having trouble working out where to put the onExit and onEnter state callbacks.
The first option is to put it in app.js which is currently defining all of my states, however I feel that this would not be a good place as it could cause this file to blow up and become hard to read as more states are introduced and the logic gets more complex.
The second option I looked into was to put it into a controller (I have one for each state), however from researching it doesn't seem to be best practice to do this.
The third option is to create a service that is resolved, however with this option I would end up with either a giant service full of state change functions for each of the states (not decoupled) or an additional service per state which would contain the state change functionality, and I worry that would increase project complexity.
What is the standard way to achieve this?
Are there any other options that I am missing?
Our strategy for this has been to disregard the onEnter and onExit on the state object, because as you are discovering, they feel like they are in the wrong place in terms of separation of concerns (app.js).
For onEnter: we handle setup in an activate() function in each controller, which we manually execute inside the controller. This happens to also match the callback that will get executed in Angular 2.0, which was not an accident ;).
function activate() {
// your setup code here
}
// execute it. this line can be removed in Angular 2.0
activate();
For onExit: We rarely need an exit callback, but when we do, we listen for the $scope $destroy event.
$scope.$on("$destroy", function() {
if (timer) {
$timeout.cancel(timer);
}
});

Ajax / Json How to run an INSERT/UPDATE into mysql

Again related with my weekend project, I'm trying to learn a bit more of web-development. So I'm putting in the list of features i want to implement, some stuff i absolutely have no idea how to do.
I've been reading tutorials on how to use ajax, but i can't find a simple one, that i can copy-paste (with one or two changes) to see it work before i go into the how it works.
What I've been searching is just a simple example on an ajax function, that triggers a mysql insert or update. Anyone as a simple example on how to do this? I think it would prove a nice start to learn it. (Ajax or Json are both ok).
Correct me if I'm mystaken: I'm basing myself on this tutorial. So as obviously the client side doesn't have access to database calls, what I should do, would be something like creating a code snippet to add stuff to the database right? For example create an "addcomment.php" that can be called with xhr.open(GET, "addcomment.php?comment=mycomment", true);
Sounds like you got it right. Use Ajax to call a server side script which then does the database work for you.
A good setup is to use a framework like jQuery on the client side. This framework will encode and decode JSON automatically. On the server side you could create a class that handles all the ajax (or rather, ajaj, since we are using JSON) requests. Here is a short PHP file that shows the general idea. Add more elements to the functionMap array, and add the respective functions to the class.
class Ajaj{
private $callback = "";
private $functionMap = array( "select" => 'getIt');
function Ajaj(){
if(array_key_exists('jsoncallback',$_GET)){
$this->callback=$_GET['jsoncallback'];
}
}
function parse(){
echo "$this->callback(";
if(array_key_exists('action', $_POST)){
$action = $_POST['action'];
if(array_key_exists($action, $this->functionMap)){
echo $this->functionMap[$action];
}
}else{
echo "{}";
}
echo ")";
}
function getIt(){
return json_encode(//get the database stuff here);
}
}
$ajaj = new Ajaj();
$ajaj->parse();

Resources