0

How can i send auth header, when test codeception rest api?

What i have now:

  1. Yii2 project
  2. "codeception/module-yii2": "^1.0.0"
  3. "codeception/module-rest": "^1.3"
  4. Generated test class by command codecept generate:cest api TestName

My class with test

 class CreateWorkspaceCest
 {
    public function _before(ApiTester $I)
    {

    }

    public function successCreate(ApiTester $I)
    {
        $title = 'create test';
        $description = 'test description';

        $I->sendPost('/workspace/create', [
            'title' => $title,
            'description' => $description,
        ]);

        $I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK); // 200
        $I->seeResponseIsJson();

        $I->seeResponseContainsJson([
            'title' => $title,
            'description' => $description,
            'status' => 'active',
        ]);
    }
}

Now it fails with 403 code, because backend expects header JWT-Key: <TOKEN>

How can i send auth header in sendPost And where it is better to store auth token in one place to avoid code duplication, during writing tests?

1 Answer 1

2

Codeception has a method called haveHttpHeader you can add any header using it.

This is documented half-way down this page. There is also a section on authorization on this other page.

There are a few built-in authorization methods, like amBearerAuthenticated, amAWSAuthenticated, but I believe that there isn't a specific method for JWT.

 class CreateWorkspaceCest
 {
    public function _before(ApiTester $I)
    {

    }

    public function successCreate(ApiTester $I)
    {
        $title = 'create test';
        $description = 'test description';

        // You can add any header like this:
        $I->haveHttpHeader('Content-Type', 'application/json');
        $I->haveHttpHeader('Authorization', 'Bearer user-one-access-token');

        // To add the header that you show in the question, you can use:
        $I->haveHttpHeader('JWT-Key', '<TOKEN>');

        $I->sendPost('/workspace/create', [
            'title' => $title,
            'description' => $description,
        ]);

        $I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK); // 200
        $I->seeResponseIsJson();

        $I->seeResponseContainsJson([
            'title' => $title,
            'description' => $description,
            'status' => 'active',
        ]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.