Giter Site home page Giter Site logo

easygraphql / easygraphql-tester Goto Github PK

View Code? Open in Web Editor NEW
311.0 9.0 34.0 1.25 MB

Test GraphQL queries, mutations and schemas on an easy way! πŸš€

Home Page: https://easygraphql.com/docs/easygraphql-tester/overview

License: MIT License

JavaScript 100.00%
graphql graphql-schema graphql-tools

easygraphql-tester's Introduction

easygraphql

Main page of easygraphql

easygraphql-tester's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

easygraphql-tester's Issues

Error when combined with gql schema

I'm trying to use EasyGraphQLTester with apollo and the gql template literals. I'm new to the GraphQL-world so combining apollo with EasyGraphQLTester might not even be valid use-case. But if it should be possible it would be nice to have an example of a correct setup in the readme.

I'm getting the following error:

    TypeError: Cannot read property 'types' of undefined

      14 | 
      15 |   beforeEach(() => {
    > 16 |     tester = new EasyGraphQLTester(typeDefs);
         |              ^
      17 |   });
      18 | 
      19 |   test("validate schema", () => {

      at buildClientSchema (node_modules/graphql/utilities/buildClientSchema.js:57:61)
      at buildGraphQLSchema (node_modules/easygraphql-tester/utils/buildGraphQLSchema.js:15:28)
      at new Tester (node_modules/easygraphql-tester/lib/tester.js:27:22)
      at Object.beforeEach (src/schema.test.js:16:14)

And this is the code:

const EasyGraphQLTester = require("easygraphql-tester");
const { gql } = require("apollo-server-express");

const typeDefs = gql`
  type Query {
    name: String!
  }
`;

describe("schema validation", () => {
  let tester;

  beforeEach(() => {
    tester = new EasyGraphQLTester(typeDefs);
  });

  test("validate schema", () => {
    const validQuery = `
          {
            name
          }
        `;

    tester.test(true, validQuery);
  });
});

example does not work

'use strict'

const { GraphQLSchema, GraphQLObjectType, GraphQLString } = require('graphql')
const EasyGraphQLTester = require('easygraphql-tester')

const schema = new GraphQLSchema({
    query: new GraphQLObjectType({
        name: 'RootQueryType',
        fields: {
            hello: {
                type: GraphQLString,
                resolve() {
                    return 'world'
                },
            },
        },
    }),
})

const tester = new EasyGraphQLTester(schema)

Error

trofimov@trofimov-PC:~/Documents/projects/openhouse/openh/back-next$ node test.js
/home/trofimov/Documents/projects/openhouse/openh/back-next/node_modules/easygraphql-parser/node_modules/graphql/utilities/buildClientSchema.js:57
  var typeIntrospectionMap = (0, _keyMap.default)(schemaIntrospection.types, function (type) {
                                                                      ^

TypeError: Cannot read property 'types' of undefined
    at buildClientSchema (/home/trofimov/Documents/projects/openhouse/openh/back-next/node_modules/easygraphql-parser/node_modules/graphql/utilities/buildClientSchema.js:57:71)
    at schemaParser (/home/trofimov/Documents/projects/openhouse/openh/back-next/node_modules/easygraphql-parser/lib/schemaParser.js:222:28)
    at new Tester (/home/trofimov/Documents/projects/openhouse/openh/back-next/node_modules/easygraphql-tester/lib/tester.js:28:25)
    at Object.<anonymous> (/home/trofimov/Documents/projects/openhouse/openh/back-next/test.js:20:16)
    at Module._compile (internal/modules/cjs/loader.js:738:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:749:10)
    at Module.load (internal/modules/cjs/loader.js:630:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:570:12)
    at Function.Module._load (internal/modules/cjs/loader.js:562:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)

help me please

queryParser with fragments

I am using Github API v4 schema (see attached file), for a simple query: "show me the issues of the actual viewer".

Running this query produce an error:

There is no query called issues on the Schema

because "issues" is not wrapped by "viewer", then not matching the schema. I debugged the code, and it is coming from:

parsedQuery = queryBuilderFromFragment(graphQuery.definitions)

easygraphql-tester = v3.0.4

@estrada9166 do you have some hint regarding handling fragments? may be some example?

const appQuery = graphql`
  query appQuery {
    viewer {
      ...issues_viewer
    }
  }

  fragment issues_viewer on User
    @argumentDefinitions(
      count: {type: "Int", defaultValue: 10}
      cursor: {type: "String"}
      orderBy: {
        type: "IssueOrder"
        defaultValue: {field: CREATED_AT, direction: DESC}
      }
    ) {
    issues(first: $count, after: $cursor, orderBy: $orderBy)
      @connection(key: "viewer_issues") {
      edges {
        node {
          ...issuesNode @relay(mask: false)
        }
      }
    }
  }

  fragment issuesNode on Issue @relay(mask: false) {
    id
    title
    repository {
      name
    }
    viewerDidAuthor
    state
  }
`;

schema.graphql.txt

Support for custom scalar validation

Thanks for this great library! I would like to be able to test validations on custom scalars.

If I have a schema like so

gql`
scalar EmailAddress

type Lead {
  email: EmailAddress!
}
`

And if I load a resolver for EmailAddress in my resolvers, I want the ability to test that my validator is correctly hooked up to the EmailAddress tag in the graphQl block. Notice that testing this connection is not the same as testing the EmailAddress resolver in isolation. Is there currently a way to do this? If not, can the feature be added?

Issues with [email protected]

Our tests started to fail after upgrading to [email protected]:

  ● Test suite failed to run

    Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: undefined

      13 |     },
      14 |   });
    > 15 |   const tester = new EasyGraphQLTester(schema);

my guess is that somewhere introspectionQuery from graphql is used. but in v15 graphql doesn't export introspectionQuery anymore, instead it exports getIntrospectionQuery function

Support for GraphQL Unions - TypeError: Cannot read property 'type' of undefined

From the code it looks like it expects all types to have fields. The GraphQLUnionType does not support fields, but the getTypes() on this type would expose each type with these fields.

In the validate fixture I could flatten the types in fields to expand the fields available for validating.

..line 89

  • const fields = selectedType.fields
  • const fields = selectedType.fields.concat([].concat.apply([], selectedType.types.map(selectedType => schema[selectedType].fields)));

If I get time next week I will create a unit test for this.

Support custom mocks on the schema

Add custom mocks to the schema on the moment of initialization the tester (const tester = new EasyGraphQLTester(schemaCode)).

To get an idea of how to do it check this link

Add expected argument to test

Add expected argument to test, it should receive as third parameter the expected result to test and also add to the lib to check if the test pass βœ… or fail ❌ compared to the expected argument.

An in-range update of graphql is breaking the build 🚨

The dependency graphql was updated from 14.3.1 to 14.4.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

graphql is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of graphql is breaking the build 🚨

The dependency graphql was updated from 14.5.8 to 14.6.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

graphql is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Implement coverage

Implement some coverage tool, so we can track the UT and improve those!

Test mutation with parameter of scalar type doesn't work

Fails when test a mutation if the mutation doesn't declare its parameters as input, throws Error: Variables are missing.

Test code:

const EasyGraphQLTester = require('easygraphql-tester')
const typeDefs = `
type Mutation {
  greet(name: String!): String!
}
`
const tester = new EasyGraphQLTester(typeDefs)

tester.test(true, `mutation {
  greet(name: "Joe")
}`)

tester.test(false, `mutation {
  greet(name: 42)
}`)

Stacktrace:

/home/leosuncin/Workspaces/CreativeZero/system-information/node_modules/easygraphql-tester/lib/queryParser.js:115
      throw new Error('Variables are missing')
      ^

Error: Variables are missing
    at queryParser (/home/leosuncin/Workspaces/CreativeZero/system-information/node_modules/easygraphql-tester/lib/queryParser.js:115:13)
    at Tester.mock (/home/leosuncin/Workspaces/CreativeZero/system-information/node_modules/easygraphql-tester/lib/tester.js:31:25)
    at Tester.test (/home/leosuncin/Workspaces/CreativeZero/system-information/node_modules/easygraphql-tester/lib/tester.js:85:12)
    at Object.<anonymous> (/home/leosuncin/Workspaces/CreativeZero/system-information/backend/__test__/test.js:9:8)
    at Module._compile (internal/modules/cjs/loader.js:722:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:733:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:775:12)

How to use test.mock if result is a Union type

In this example in my code, the query returns always empty:

it('Should return store by id', () => {
   const query = `
     query($id: ID, $slug: String) {
       store(id: $id, slug: $slug) {
         ... on Store {
           id
           name
           slug
         }
       }
     }
   `;

   const fixture = {
     data: {
       store: {
         id: '1',
         name: 'AnyoneStore'
       }
     }
   };

   const variables = {
     id: "1"
   };

   const { data: { store } } = tester.mock({ query, fixture, variables });

  // store
 / / {}

Improve documentation

Improve documentation to make it easier to understand all the possible cases of usage and options there are.

Setup header properties on `.graphql` function

I was wondering if we have a way to setup header properties through the .graphql function. I'm using apollo server and it seems that using it is bypassing some middlewares(like authentication/authorization stuff).

example on what would be nice to have:

tester.graphql(query, undefined, undefined, { isLocal: false, headers: { authorization: 'Bearer JWT AshufewmrgfddJWT_TOKEN_EX' } })
  .then(result => console.log(result))
  .catch(err => console.log(err))

Feature Request: Query variables as a param

When using the schema tester, I was surprised to find that you can't pass variables in as a third param when using queries - you have to include the values in the query. Mutations take a third object param, just not queries.

I'd be happy to put in a PR if there are no objections.

Run Command and set up

I am writing it very first time, having a resolver like

const getCountries = (context) => {
const { cookies = {}, traceId } = context;
const httpClient = new HttpClient(
cookies[OAUTH_ACCESS_TOKEN], true,
{
TraceId: traceId
}
);

const url = URL.RESOURCES.SERVICE_URL.GET_COUNTRIES_URL;
return httpClient.restService('get', url)
.then((response) => {
logger.info(response.body)
return response.body;
})
.catch((error) => {
logger.info("Error in getting issue suggestions", JSON.stringify(error));
const { httpDetails:{ statusCode } } = error
return { statusCode };
});
};

module.exports = getCountries;

Could you please let me know, what would be best way to write it. I am not able to see the commands in the document to run the test cases.

Question about readme

I'm confused by this sentence in the readme:

It will check:

* If the operation name is defined on the schema.

Operation names are part of the query and they're not defined in the schema, so what do you mean by this?

Mock data should include top-level fields

This library is super nice for testing! But I would like to request a breaking change. I could work on a pull request if you think that the change is a good idea.

I want to set up some test code so that when a function being tested makes a GraphQL query I use a stub to intercept the request, and use tester.mock to respond with fake data that has the correct shape. The problem is that the data returned from tester.mock is composed of the value of a top-level field in the query, as opposed to an object that contains the top-level field as a property. For example when running this query in https://www.graphqlbin.com/v2/6RQ6TM:

{
  skywalker: allPersons(filter: { name: "Luke SkyWalker" }) {
    name
    birthYear
  }
}

I expect the data in the response to look like this:

{
  "skywalker": [
    {
      "name": "Luke Skywalker",
      "birthYear": "19BBY"
    }
  ]
}

But calling tester.mock() using the same schema and query produces this:

[
  {
    "name": "Luke Skywalker",
    "birthYear": "19BBY"
  }
]

To use this mock data in my tests I have to either hard-code the top-level field name and wrap the mock data under an object with that property, or parse the query a second time to pull out the top-level field name.

I think that the first result - an object with the property "skywalker" - would be a more useful result.

Remote Schema

I'm wondering if its possible to run tests on a remote schema so that we can test clients against deployed servers?

Passing invalid parameters to a query doesn't fail the test.

See the example below, the parameter thisIsAnInvalidParameter probably should return an error and fail the test, but it seemed to be ignored.

    test('Invalid parameters', () => {
        const invalidQuery = `
        {
            voyage(thisIsAnInvalidParameter: "1234")
            {
                Reference
                Status
            }
        }
        `;
        tester.test(false, invalidQuery);
    });

Support for graphql-compose SchemaComposer.buildschema()

I am getting this error when providing a GraphQLSchema built with graphql-compose.github using SchemaComposer.buildschema()

    Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: undefined

    > 46 |     const tester = new EasyGraphQLTester(schema);
         |                    ^

      at devAssert (node_modules/easygraphql-tester/node_modules/graphql/jsutils/devAssert.js:12:11)
      at buildClientSchema (node_modules/easygraphql-tester/node_modules/graphql/utilities/buildClientSchema.js:47:125)
      at buildGraphQLSchema (node_modules/easygraphql-tester/utils/buildGraphQLSchema.js:16:28)
      at new Tester (node_modules/easygraphql-tester/lib/tester.js:27:22)
      at Object.<anonymous> (my_file.js:46:20)

the code I am testing:

  it("should return schema types", async () => {
    const schema = await getSchema(); // returns a schemaComposer.buildSchema();
    const tester = new EasyGraphQLTester(schema);
    const query = gql`{ // using graphql-tag, also tried without it
      __schema {
        types {
          name
        }
      }
    }`;
    const result = await tester.graphql(query);

    expect(result).toHaveProperty("data");
  });

Appreciate any hint! Thanks!

'Type "User" not found in document'

I've loaded in my schema, but when I run tester = new EasyGraphQLTester(schemaCode) I just get an error saying Type "User" not found in document

I can't figure out what this means... My schema has no user Type so why does it want it

Performance issue with multiple nested queries and nested tree of queries.

It took 640 seconds for me to run a single test on my schema.

Every query is rather long, 10-20 item in each and some refrence 1-3 other queries.
I can send my schema in a private message if you need testing data.

It seem to be the worst with nested tree of queries, simplefied example:

type Booking {
  id: ID!
  details: [Detail]
}
type Detail {
  dimensions: [Dimension]
}
type Dimension {
  weight: String
}
type Query {
      booking(id: ID!): Booking
}

The query I'm using for my test:

{
  booking(id:"123456") {
      id
  }
}

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

How can I test my middlewares?

Can you show me an example of how can i test my middlewares?
I want to test that my queries can only be accessed if the correct jwt token is passed through the request Authorization header. I'm using graphql-yoga middleware. Here's an example of my graphql server:

const server = new GraphQLServer({
    typeDefs: './src/schemas/schema.graphql',
    resolvers,
    middlewares: [permissions],   // <-- here's where I pass in my middleware
    context: request => {
        return {
            ...request,
            prisma,
        };
    },
});

Here's what I intend to do, e.g.:

test('only authorized user can see this', async () => {
        const query = `
             query user($id: ID!){
                user(id: $id) {
                    id
                    email
                    name
                }
            }
        `;
        const args = {
            id: 'foo-bar-id',
        };
        const result = await tester.graphql(
            query,
            {},
            { prisma },
            args,
        );
         expect(result.errors[0].message).to.be.eq(
             'Error!! Unauthorized request',
         );

Refactor tests

Refactor tests and order them, so those tests match the same format and the related ones are on the same files.

Issue with extend type Query

Hi,

So I just started using easygraphql-tester, however, I ran into a problem.

My applications is structure by using stitching to achieve modularisation.

Therefore, my schema.js, looks something like this:
`
const { gql } = require("apollo-server");

const user = require("./models/user/user.schema");

const root = gql`
type Query {
root: String
}

type Mutation {
root: String
}
`;

module.exports = [root, user];

`

User.js
`const { gql } = require("apollo-server");
const user = gql'
extend type Query {
getCurrentUser: User
}
extend type Mutation {
signupUser(username: String!, email: String!, password: String!): AuthToken
signinUser(username: String!, password: String!): AuthToken
}
type AuthToken {
token: String!
}
type User {
_id: ID
username: String!
password: String!
email: String!
joinDate: String
tokens: [Token]
}
';

module.exports = user;`

Issue is that, when I try to build like this
const typeDefs = require('./schema.js'); let tester = new EasyGraphQLTester(typeDefs);

This returns an error saying

TypeError: Must provide Source. Received: { kind: "Document", definitions: [[Object], [Object]], loc: [Object] }

I think the issue is with the syntax extend type Query.

Is there a workaround?

An in-range update of graphql is breaking the build 🚨

The dependency graphql was updated from 14.4.2 to 14.5.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

graphql is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v14.5.0

v14.5.0 (2019-08-22)

New Feature πŸš€

Bug Fix 🐞

Docs πŸ“

Polish πŸ’…

42 PRs were merged

Internal 🏠

14 PRs were merged

Dependency πŸ“¦

7 PRs were merged

Committers: 4

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Testing async resolvers

I have a problem testing async resolvers.
I get an error which says "Promise returned by test never resolved".

How to get rid of it? I need async in the resolvers ofcourse.

Ability to pass options to constructor to customize behavior of makeExecutableSchema

Currently, the library does not allow custom options to be passed to makeExecutableSchema in tester.js.

Is it possible to allow a third options parameter to be passed to the tester constructor so users can define optional variables below:

const { makeExecutableSchema } = require('apollo-server');

const jsSchema = makeExecutableSchema({
  typeDefs,
  resolvers,
  logger, // optional
  allowUndefinedInResolve = false, // optional
  resolverValidationOptions = {}, // optional
  directiveResolvers = null, // optional
  schemaDirectives = null,  // optional
  parseOptions = {},  // optional
  inheritResolversFromInterfaces = false  // optional
});

in order to customize the logging and validation behavior of their tests so unnecessary validation errors are not thrown if unwanted?

mock

I have the following query, and some troubles to mock it. (using v 3.0.6)

      query trialQuery {
        viewer {
          name
          isHireable
          repository(name: "test") {
            issues(first: 5, orderBy: {field: CREATED_AT, direction: DESC}) {
              pageInfo {
                hasPreviousPage
                hasNextPage
                startCursor
                endCursor
              }
              totalCount
              edges {
                node {
                  id
                  title
                  viewerDidAuthor
                  state
                }
              }
            }
          }
        }
        licenses {
          name
        }
      }
    `;

Situation:

  • without licenses part, it is possible to mock it (removing the "viewer"), e.g.:
{
    isHireable: false,
    name: 'martin',
    repository: {
      issues: {
        pageInfo: {
          hasPreviousPage: false,
          hasNextPage: true,
          startCursor:
            'Y3Vyc29yOnYyOpK5MjAxOS0wMS0xNFQxMDowNTo0NSswMTowMM4XxS65',
          endCursor: 'Y3Vyc29yOnYyOpK5MjAxOS0wMS0xNFQxMDowNDo0MyswMTowMM4XxS1p',
        },
        totalCount: 25,
        edges: [
          {
            node: {
              id: 'MDU6SXNzdWUzOTg3OTg1MjE=',
              title: 'test 25',
              viewerDidAuthor: true,
              state: 'OPEN',
            },
          },
...
  • I would like to have viewer, as it is more semantic, but especially it is necessary if we want to query multiple resources at once, in the example above, no way to mock licenses.

One more thing, if I try to define variables (global), I get an error:

      query trialQuery($repo: String!, $count: Int, $orderBy: IssueOrder) {
        viewer {
          name
          isHireable
          repository(name: $repo) {
            issues(first: $count, orderBy: $orderBy) {
...

Error: repo variable is not defined on viewer arguments

@estrada9166 Could you please give me some hint?

Support for gql

I would love to use gql tag in the query/mutation to have autocomplete. it works without using resolvers, but when I use resolvers in the tester, I cannot use the gql tag

An in-range update of easygraphql-mock is breaking the build 🚨

The dependency easygraphql-mock was updated from 0.1.14 to 0.1.15.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

easygraphql-mock is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 3 commits.

  • 6ced941 0.1.15
  • ac258e6 Update easygraphql-parser to the latest version πŸš€ (#51)
  • 6b2b3d0 Update husky to the latest version πŸš€ (#50)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Test mutation with input type Upload

Hi, I want to test my mutation which have input type Upload. How to do that with EasyGraphQL?

I know we can pass the expected input on the third parameter (after Call test from tester).

const EasyGraphQLTester = require('easygraphql-tester')
const fs = require('fs')
const path = require('path')

const schemaCode = fs.readFileSync(path.join(__dirname, 'schema', 'schema.gql'), 'utf8')
const tester = new EasyGraphQLTester(schemaCode)

const mutation = `
  mutation CreateUser{
    createUser {
      email
    }
  }
`
tester.test(true, mutation, {
  banner: '',
  username: 'test',
  fullName: 'test',
  password: 'test'
})

on that above case.. if banner is input type Upload, how to do that in easygraphql?

Syntax Error: Unexpected <EOF>

Hello
After invoke EasyGraphQLTester constructor i have the Syntax Error: Unexpected

I did console the Lexure which parses on that time and this lexure is #imports

Test query of scalar type doesn't work

It fails when try to query a scalar type not an object, and get TypeError: Cannot read property 'selections' of undefined

You can try the next example code:

const EasyGraphQLTester = require('easygraphql-tester')
const typeDefs = `
type Query {
  name: String!
}
`
const tester = new EasyGraphQLTester(typeDefs)

tester.test(true, `{
  name
}`)

Stacktrace:

node_modules/easygraphql-tester/lib/queryParser.js:35
    parsedType.fields = selectedFields(element.selectionSet.selections)
                                                            ^

TypeError: Cannot read property 'selections' of undefined
    at selections.forEach.element (node_modules/easygraphql-tester/lib/queryParser.js:35:61)
    at Array.forEach (<anonymous>)
    at queryBuilder (node_modules/easygraphql-tester/lib/queryParser.js:31:14)
    at queryParser (node_modules/easygraphql-tester/lib/queryParser.js:111:19)
    at Tester.mock (node_modules/easygraphql-tester/lib/tester.js:24:25)
    at Tester.test (node_modules/easygraphql-tester/lib/tester.js:68:12)
    at Object.<anonymous> (backend/__test__/test.js:10:10)
    at Module._compile (internal/modules/cjs/loader.js:722:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:733:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)

TypeError: Cannot read property 'type' of undefined

I have a valid Query that passes with tester.test however when I tester.mock with a fixture, then I'm seeing:

TypeError: Cannot read property 'type' of undefined
      at validateFixture (node_modules/easygraphql-tester/utils/fixture.js:50:27)
      at validateFixture (node_modules/easygraphql-tester/utils/fixture.js:100:19)

I debugged and it appears the issue is related to a simple name of type String which the mocker has no selectedType, hence the error at this line: https://github.com/EasyGraphQL/easygraphql-tester/blob/master/utils/fixture.js#L46

  if (schema[selectedType.type]) {

If I simply add a null check, all my tests pass:

  if (selectedType && schema[selectedType.type]) {

I'm happy to open a PR here, but I'd first want a core dev here to weigh in on what might be the issue and if this would be a valid check to simply add a null check on selectedType

GraphQL 16 support?

Hello,

Do you have any plans to have support for GraphQL 16 or a suggested package to replace easygraphql-tester?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.