0

I wonder if it's possible to define some custom JsonType for validation API responses through seeResponseMatchesJsonType method. I mean, let's suppose I have response with a structure:

[
   'id' => 'integer',
   'name' => 'string',
   'address' => [
      'street' => 'string',
      'city' => 'string'
   ]
]

Obviously this structure has complex type address embedded and in the whole app such type might be used several times so I would like to write simply:

$I->seeResponseMatchesJsonType([
   'id' => 'integer',
   'name' => 'string',
   'address' => 'addressType'
]);

Without rewriting this embedded structure all the time. How can I achieve it in Codeception?

Tomasz Kapłoński
  • 1,320
  • 4
  • 24
  • 49

1 Answers1

1

Yes you can do this by using method addCustomFilter from \Codeception\Util\JsonType class.

/**
     * Adds custom filter to JsonType list.
     * You should specify a name and parameters of a filter.
     *
     * Example:
     *
     * ```php
     * <?php
     * JsonType::addCustomFilter('email', function($value) {
     *     return strpos('@', $value) !== false;
     * });
     * // => use it as 'string:email'

     *
     * // add custom function to matcher with `len($val)` syntax
     * // parameter matching patterns should be valid regex and start with `/` char
     * JsonType::addCustomFilter('/len\((.*?)\)/', function($value, $len) {
     *   return strlen($value) == $len;
     * });
     * // use it as 'string:len(5)'
     * ?>
     * ```
     *
     * @param $name
     * @param callable $callable
     */
    public static function addCustomFilter($name, callable $callable)
    {
        static::$customFilters[$name] = $callable;
    }
ermacmkx
  • 439
  • 5
  • 12