flask-jwt-extended: Fake Authorization Header during testing (pytest)

@jwt_required only works in the context of a Flask request. You can send in the access token using the flask test client with the headers name option:

def test_foo():
    test_client = app.test_client()
    access_token = create_access_token('testuser')
    headers = {
        'Authorization': 'Bearer {}'.format(access_token)
    }
    response = test_client.get('/foo', headers=headers)
    # Rest of test code here

Optionally, you could unwrap the decorated method by using the __wrapped__ property. In your case, it would look like:

method_response = get_all_projects.__wrapped__()

Note that any calls to the flask-jwt-extended helper functions in your endpoint (such as get_jwt_identity(), current_user, etc). would not work this way, as they require a flask request context. You could get around this by mocking the flask-jwt-extended functions used inside the function, but that may be harder to maintain as the application grows and changes.


One option for faking JWT tokens during unit testing is to patch jwt_required. More specifically patch the underlying function verify_jwt_in_request. This mocks the decorator and removes the need to create authorization tokens for the test.

from unittest.mock import patch


@patch('flask_jwt_extended.view_decorators.verify_jwt_in_request')
def test_get_all_projects(mock_jwt_required):
    # ...

Old topic, but here's some additional insight about how to test functions with @jwt_required:

@pytest.fixture(scope="function", autouse=True)
def no_jwt(monkeypatch):
  """Monkeypatch the JWT verification functions for tests"""
  monkeypatch.setattr("flask_jwt_extended.verify_jwt_in_request", lambda: print("Verify"))