Summer Sale! All accounts are 50% off this week.

karam mustafa's avatar

How to mock helper function ?

Suppose that we have a helper function in file helpers, and this file is loaded from the composer.json file by autoloading, like this

"autoload": {
        "classmap": [
            "database",
            "app/helpers"
        ],
        "psr-4": {
            "App\": "app/"
        },
        "files": [
            "app/helpers/helpers.php"
        ]
    },

and inside this file, there is our function

if(! function_exists('getAnyValue')){
    /**
     * function to use in laravel application as a helper function
     */
    function getAnyValue()
    {
        return 'test';
    } 

}

now we want to use this function in a controller, like this

class myController extends Controller
{
    public function index()
    {
        return  getAnyValue();
    }
}

and the route is

    Route::get('test-route', [myController::class, 'index']);

so if we want to test this route, the unit test throw an error

Call to undefined function getAnyValue()

therefore my question is how to mock this function?

0 likes
1 reply

Please or to participate in this conversation.