How do I pass the Context type from the async graphql crate into a test?

Official Context doc: Context - Async-graphql Book

Anyone worked with the async graphql crate here?

I have a create_book function as part of my MutationResolver that receives the graphql async Context type in order to pull out the Datastore struct.

use async_graphql::{Context, Object, Result, ID};

async fn create_book(
    &self,
    ctx: &Context<'_>,
    table: String,
    name: String,
    author: String,
) -> Result<Book> {
    let data_store = ctx.data_unchecked::<Datastore>();
    let res = create_book(data_store, table, name, author).await.unwrap();
    Ok(res)
}

/
//ERROR MESSAGE with Context below: expected value, found type alias `Context`
//can't use a type alias as a constructor

 #[tokio::test]
async fn test_01_try_create_book() {
    let table = "users".to_string();
    let name = "HP".to_string();
    let author = "JKR".to_string();

    let test = MutationResolver
        .create_book(&Context, table, name, author)
        .await
        .unwrap();
}

How come my test is complaining that it can't take Context as a param but no corresponding issues with the create_book function taking the Context type?

I don't think testing your MutationResolver without a Schema is possible or if it is possible, it is not really feasible, as the Schema takes care of the context for you (see here). Personally I test my graphql APIs through the schema, parsing my query string with Schema::execute and see if my mutations or queries work as expected.

1 Like

Thank you so much!

I was just wondering if you could share a test for my reference? I've been banging against my head against this the whole day now.

If not possible then all good!

This is how I'd write a test for a mutation (I didn't acutally test this, there may be syntax issues here):

 #[tokio::test]
async fn test_01_try_create_book() {
    let schema = Schema::build(EmptyQuery, MutationResolver, EmptySubscription)
        .data(/* the data you wish to attach to your context */)
        .finish();


    schema.execute(
        r#"
            mutation {
                createBook(
                    table: "users",
                    name: "HP",
                    author: "JKR"
                )
            }
        "#,
    )
    .await
    .into_result()
    .unwrap();
}
1 Like

Thanks for everything! Absolute lifesaver!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.