Just begun creating some unit tests for my controllers within my CakePHP application however I am completely flummoxed on how I should create a mock for the Auth Component, I have read the CookBook and thought I had it right, but keep getting thrown this error.
Error: Call to a member function allow() on a non-object
Within the controller I am testing there is a beforeFilter function with the following code:
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('create');
}
Within my test I have included the following:
$Leagues = $this->generate('Leagues', array(
'components' => array(
'Auth'
)
));
I have played around with staticExpects() also but it doesn't seem to have much affect (I am also unsure what I need to put in to staticExpects()).
What do you mean by mock? Just stuffing an object with data that you set? The error you're getting is because you need to use
$this->Auth->allow(array('create'))
Found the issue - I have included the Auth component within AppController.php, and not specifically within the controller I was trying to test. By including it with my controller specifically the errors have gone away.
Related
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
I am trying to mock a CakePHP 3 component which checks if the user is allowed to view the page or not.
I tried this:
$authComponent = $this->getMockBuilder(App\Controller\Component\AuthorizationComponent::class)
->getMock();
$authComponent
->method('isAuthorized')
->willReturn($this->returnValue(true));
However, when running the test, it says:
Trying to configure method "isAuthorized" which cannot be configured because it does not exist, has not been specified, is final, or is static
Most probably I wrongly created the mock. Can anyone tell me how to do it correctly?
Specify mocked methods with setMethods() before getMock():
$authComponent = $this
->getMockBuilder(App\Controller\Component\AuthorizationComponent::class)
->setMethods(['isAuthorized'])
->getMock();
Running ember 1.13.6 and ember-cli
I have an ember component which I am trying to acceptance test. It's state is very closely tied to the state of a service within my app and so I would like to directly access that service and change its properties from within my acceptance test.
I have been trying things along the lines of
this.application.__container__.lookup['service:side-bar'])
and
this.application.__container__.cache['service:side-bar'])
but I cannot seem to get the actual active service singleton which my app is using and which I could call get() and set() on.
if I try to use Ember.inject.service i get an obscure error Uncaught TypeError: Object.defineProperty called on non-object(…) which sort of sounds like a bug
I'm successfully getting at a service in 1.13.x by doing something like this:
let myService;
module("Acceptance | xxxxx", {
beforeEach() {
this.application = startApp()
myService = this.application.__container__.lookup('service:my-service');
}
});
Your problem might be that you're trying to use array notation (lookup['my-service']) rather than method invocation (lookup('my-service')).
Hope this helps!
I'm trying to unit test my controllers in Laravel 5, but have serious issues wrapping my head around it. It seems as I have to trade the great short-hand functions and static classes for dependency injected equivalents if I actually want to do isolated unit testing.
First off, what I see in the documentation as "Unit testing", is not unit testing to me. It seems more like functional testing. I can not test a controller function isolated, as I will have to go through the entire framework, and will need to actually seed my database if I have any code interacting with my database.
So, in turn, I want to test my controllers isolated of the framework. This is however proving to be quite difficult.
Let's look at this example function (I've kept out some parts of this function for the sake of the question):
public function postLogin(\Illuminate\Http\Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials, $request->has('remember')))
{
return redirect()->intended($this->redirectPath());
}
}
Now, the problem arises in the final lines. Sure, I can mock the Request instance that's sent to the function, that's no issue. But how am I going to mock the Auth class, or the redirect function? I need to rewrite my class/function with dependency injection like this:
private $auth;
private $redirector;
public function __construct(Guard $auth, \Illuminate\Routing\Redirector $redirector)
{
$this->auth = $auth;
$this->redirector = $redirector;
}
public function postLogin(\Illuminate\Http\Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if ($this->auth->attempt($credentials, $request->has('remember')))
{
return $this->redirector->intended($this->redirectPath());
}
}
And I end up with a convoluted unit test, full of mocks:
public function testPostLoginWithCorrectCredentials()
{
$guardMock = \Mockery::mock('\Illuminate\Contracts\Auth\Guard', function($mock){
$mock->shouldReceive('attempt')->with(['email' => 'test', 'password' => 'test'], false)->andReturn(true);
});
$redirectorMock = \Mockery::mock('\Illuminate\Routing\Redirector', function($mock){
$mock->shouldReceive('intended')->andReturn('/somePath');
});
$requestMock = \Mockery::mock('\Illuminate\Http\Request', function($mock){
$mock->shouldReceive('only')->with('email', 'password')->andReturn(['email' => 'test', 'password' => 'test']);
$mock->shouldReceive('has')->with('remember')->andReturn(false);
});
$object = new AuthController($guardMock, $redirectorMock);
$this->assertEquals('/somePath', $object->postLogin($requestMock));
}
Now, if I had any more complex logic that would, for example, use a model, I'd have to dependency inject that as well, and mock it in my class.
To me, it seems like either, Laravel isn't providing what I want it to do, or my testing logic is flawed. Is there any way I can test my controller functions without getting out-of-control testing functions and/or having to depedency inject standard Laravel classes, available to me anyways in my controller?
You shouldnt be trying to unit test controllers. They are designed to be functional tested via calling them through the HTTP protocol. This is how controllers are designed, and Laravel provides a number of framework assertions you can include in your tests to ensure they work as expected.
But if you want to unit test the application code contained within the controller, then you should actually consider using Commands.
Using Commands allows you to extracte the application logic from your controller into a class. You can then unit test the class/command to ensure you get the results expected.
You can then simply call the command from the controller.
In fact the Laravel documentation tells you this:
We could put all of this logic inside a controller method; however, this has several disadvantages... it is more difficult to unit-test the command as we must also generate a stub HTTP request and make a full request to the application to test the purchase podcast logic.
Is there a way to inject providers when writing unit tests using Karma(Testacular) and Jasmine in angular?
Our team decided recently to use angularjs $log to write debugging details to the console. This way we can leverage the ability to disable the logging via the $logProvider.debugEnabled() method.
angular.module("App", ["prismLogin", "ui.bootstrap"])
.config(["$routeProvider", "$logProvider",
function ($routeProvider, $logProvider) {
$routeProvider
//routes here edited for brevity
//This is the offending line, it breaks several pre-existing tests
$logProvider.debugEnabled(true);
}]);
However after adding the $logProvider.debugEnabled(true); line several of our tests no longer execute successfully, failing with the following message:
TypeError: Object doesn't support property or method 'debugEnabled' from App
So my question again, is it possible to mock the $logProvider? Or should I provide my own configuration block for the test harness?
I attempted searching for a way to mock the app module with no luck. It seems to me that using the concrete app module instead of a mock is very brittle. I would like to avoid reworking tests associated with the app module every time a change is made in the app or run configuration blocks.
The tests that are failing are units of code with no relation to the $logProvider? I feel as if I a missing something here and making things much harder than they should be. How should one go about writing tests that are flexible and are not affected by other side effects introduced in your application?
It appears that this is a know issue with angular-mocks.
Until the issue is addressed , I was able to resolve the issue by adding the following method to the angular.mock.$LogProvider definition in angular-mocks.js at line 295.
this.debugEnabled = function(flag) {
return this;
};