Home > OS >  How to test laravel pipeline
How to test laravel pipeline

Time:12-21

I am using pipeline to filter messages.

$value = app(Pipeline::class)
        ->send($value)
        ->through([
            HtmlAttributeFilter::class,
            ProfanityFilter::class,
            RemoveTags::class,
        ])
        ->thenReturn();

I want to test this code

<?php

namespace App\Filters;

use Closure;

class HtmlAttributeFilter implements FilterInterface
{
    /**
     * Handles attribute filtering removes unwanted attributes
     * @param $text
     * @param Closure $next
     * @return mixed
     */
    public function handle($text, Closure $next)
    {
        $text = str_replace('javascript:', '', $text);
        $text = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/si", '<$1$2>', $text);
        return $next($text);
    }
}

I test this code by defining custom closure but I am not sure I am doing it in right way. I wanted to mock but I couldn't figure out how to mock this object. Did anyone test pipelines before? Any help would be highly appricated.

This is how I test it

$callable = function (string $text) {
        return $text;
    };
    $text = "<html lang='tr'><link href='https://www.example.com'></html>";
    $expectedText = "<html><link></html>";
    $obj = new HtmlAttributeFilter();
    $filteredText = $obj->handle($text, $callable);
    $this->assertEquals($expectedText, $filteredText);

CodePudding user response:

I think giving it a custom closure is the right thing to do e.g. like:

public function testHtmlAttributeFilterDoesSomething() {
   $next = function ($result) {
        $this->assertEquals('expected value', $result);
        
   };
   app()->make(HtmlAttributeFilter::class)->handle('given value', $next);
} 

I don't think you need to test the entire pipeline as long as each constituent part is tested because Laravel includes tests that test whether the pipeline logic is working as intended

  • Related