Functional Testing in Laravel – Snippets

We place a heavy emphasis on functional and unit testing for client projects, which are often Single Page Apps or “Business As Usual” tools (such as inventory management, job management).

To ensure we don’t introduce any bugs to code that sometimes hasn’t been modified for years, all new code is written with tests that are automatically run.

This means when we change 1 line of code, hundreds of pieces of functionality are automatically tested and verified working before code is committed to production.

Testing snippets

Requesting a JSON object via a GET request, and asserting against the object returned:

    /**
     * @test
     * Checks sort of products
     * Checks structure of products
     */
    public function products_for_client_should_return_data(){
        $this->be($this->unprivileged_user);
        $resp = $this->call("GET", "/drygoods/products_for_client/5");
        $obj = $resp->getData();
        $this->assertEquals($obj->output->subcategories[0], "General");

    }

Call API endpoint with Basic Authentication headers, JSON body and interrogate response (in this case, that bad JSON syntax throws an appropriate error):


    /**
     * @test
     */
    public function createTokenFromOrderDetailsThrowsErrorIfSyntaxError()
    {


        $body = <<<EOT
        {
        "json": {
            "got": "snipped!"
            }
        }

    EOT;

        $uri = "/api/v1/merchants/orders";
        $id = "123";
        $secret_key = "it's a secret!";
        

        $headers = [
            'HTTP_Authorization' => "Basic " . base64_encode($id . ":" . $secret_key),
            'Content-Type' => 'application/json'
        ];

        $this->call('POST', $uri, [], [], [], $headers, $body);
        $resp = $this->response->getContent();
        $this->assertResponseStatus(400);
        $this->assertContains("Syntax", $resp);

    }
Published