# graphql-testx

> graphql-testx is a full-featured GraphQL server, based on [Graphback](https://graphback.dev/) and [Apollo Server](https://www.apollographql.com/docs/apollo-server/). With the minimum configuration required, you have a server ready for testing GraphQL clie

Latest version **0.3.0** (published 2020-01-08) · 0 weekly downloads

## Install

```sh
npm install graphql-testx
pnpm add graphql-testx
yarn add graphql-testx
bun add graphql-testx
```

Provides the command `print-schema`.

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities.

Warnings: low downloads; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.3.0 |
| Published | 2020-01-08 |
| First published | 2019-11-19 |
| Weekly downloads | 0 |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 10 |
| Unpacked size | 87.3 KB |
| Known vulnerabilities | 0 (+28 in 3 direct dependencies) |
| Install scripts | no |
| Maintainers | b1zzu |

## Links

- npm: https://www.npmjs.com/package/graphql-testx
- npm.io page: https://npm.io/package/graphql-testx

## Dependencies (10)

- [axios](https://npm.io/package/axios.md) 0.19.1
- [express](https://npm.io/package/express.md) 4.17.1
- [graphql](https://npm.io/package/graphql.md) 14.5.8
- [get-port](https://npm.io/package/get-port.md) 5.0.0
- [graphback](https://npm.io/package/graphback.md) 0.10.0
- [graphql-tag](https://npm.io/package/graphql-tag.md) 2.10.1
- [knex-cleaner](https://npm.io/package/knex-cleaner.md) 1.3.0
- [graphql-migrations](https://npm.io/package/graphql-migrations.md) 0.10.0
- [apollo-server-express](https://npm.io/package/apollo-server-express.md) 2.9.15
- [@graphback/codegen-client](https://npm.io/package/@graphback/codegen-client.md) 0.10.0

## Recent versions

- 0.3.0 (latest) — 2020-01-08
- 0.3.0-dev475.6b993cd (dev) — 2020-02-11
- 0.3.0-dev2 (next) — 2019-12-11
- 0.3.0-dev473.f4b5747 — 2020-01-29
- 0.3.0-dev472.db2a503 — 2020-01-24
- 0.3.0-dev468.818418f — 2020-01-23
- 0.3.0-dev466.b7c6560 — 2020-01-23
- 0.3.0-dev464.50488d3 — 2020-01-23
- 0.3.0-dev462.b347028 — 2020-01-17
- 0.3.0-dev460.ffe34d3 — 2020-01-16
- 0.3.0-dev458.8b371bb — 2020-01-15
- 0.3.0-dev455.86650e3 — 2020-01-15
- 0.3.0-dev453.2e9bca7 — 2020-01-15
- 0.3.0-dev449.8a97912 — 2020-01-14
- 0.3.0-dev451.12490a3 — 2020-01-14
- … 45 more at https://npm.io/package/graphql-testx/versions

## README

# graphql-testx

graphql-testx is a full-featured GraphQL server, based on
[Graphback](https://graphback.dev/) and
[Apollo Server](https://www.apollographql.com/docs/apollo-server/). With the
minimum configuration required, you have a server ready for testing GraphQL
client applications or libraries. Unlike mocking alternatives, graphql-testx
offers persistent data between queries and mutation using in-memory SQLite
database.

![graphql-testx](https://user-images.githubusercontent.com/7964685/69070551-9dc31980-0a28-11ea-8b55-97707b26693c.png)

## Getting Started

### Installation

Using npm:

```
npm install graphql-testx
```

or yarn:

```
yarn add graphql-testx
```

### Usage

```js
// create the server using a data model
const server = new TestxServer({
  schema: `
    type Item {
      id: ID!
      name: String!
      author: String
    }`
});

// start the server
await server.start();

// retrieve the server url
console.log(`Running on ${await server.httpUrl()}`);

// ...

// close the server once you finish otherwise it
// will not allow nodejs to exit
await server.close();
```

Under to hood we use Graphback to parse the Type Definitions/Data Model and
generate the GraphQL schema and resolvers. See the
[Graphback Docs on Data Model Definition](https://graphback.dev/docs/datamodel)

### Create the client

graphql-testx doesn't provide any graphql client, which means that you can use
the `server.httpUrl()` graphql endpoint with your preferred client or your own
developed client.

### What's next?

Going throw the [Examples](#examples) is the best way to start, we have
different examples that shows how to use **graphql-testx** using different
graphql clients and javascript test frameworks.

## Examples

- Testing **Apollo Client** library with **mocha**

  [graphql-testx-apollo-client-example](./examples/apollo-client)

- Testing **Offix** library with **Jest**

  [graphql-testx-offix-example](./examples/offix)

- Testing generic application with **Karma**

  [graphql-testx-karma-example](./examples/karma)

## Contributing

Read our [contributing guide](CONTRIBUTING.md) if you're looking to contribute.

## Documentation

### `TestxServer`

Generate the GraphQL server form the given Data Model and provides a set of
useful methods. The database and the GraphQL resolvers are generated by
Graphback.

```js
import { TestxServer } from "graphql-testx";

const server = new TestxServer({
  schema: `
    type Item {
      id: ID!
      name: String!
    }`
});

await server.start();

console.log(`Running on ${await server.httpUrl()}`);

await server.close();
```

#### `bootstrap(): Promise<void>`

Generate the GraphQL server, the GraphQL resolvers, the client
queries/mutations/subscriptions and the database.

```js
// server: TestxServer
await server.bootstrap();
```

#### `start(): Promise<void>`

Start or re-start the GraphQL server.

```js
// server: TestxServer
await server.start();
```

If used without calling the `bootstrap()` method it will do it for you.

If used at the first time or after the `close()` method it will start the server
to a random port on localhost.

If used after the `stop()` method it will re-start the server on the previous
port.

If the server is already running it will return immediately.

#### `stop(): Promise<void>`

Stop the GraphQL server, so that it can be restarted on the same port, and also
preserve the database.

```js
// server: TestxServer
await server.start();
await server.stop();
await server.start(); // re-start
```

It is useful to test the client behavior when the GraphQL server is not
reachable.

If the server is not running it will return immediately.

#### `close(): Promise<void>`

Close the GraphQL server and the database.

```js
// server: TestxServer
await server.start();
await server.close();
```

#### `httpUrl(): Promise<string>`

Return the http url to the GraphQL server after starting the server.

```js
// server: TestxServer
await server.start();
console.log(`Running at ${await server.httUrl()}`);
```

### `wsUrl(): Promise<string>`

Return the websocket url to the GraphQL server after starting the server.

```js
// server: TestxServer
await server.start();
console.log(`Running at ${await server.wsUrl()}`);
```

The websocket url can be used to subscribe to the server like in this example:
[./examples/apollo-client/test/subscriptions.spec.ts](./examples/apollo-client/test/subscriptions.spec.ts)

#### `cleanDatabase(): Promise<string>`

Remove all data from the database.

```js
// server: TestxServer
await server.start();

// some mutations

await server.cleanDatabase();
```

It can be useful to reset the server state to a known point before each tests.

#### `setData(data: ImportData): Promise<void>`

Clean the database and insert the passed data directly to the database without
passing through GraphQL mutations.

```js
// server: TestxServer
await server.bootstrap();
await server.setData({
  item: [
    { id: 1, name: "one" },
    { id: 2, name: "two" }
  ]
});
```

It can be useful to reset the server to an initial state before each tests
without triggering subscriptions, or data business logics.

If you don't know the database structure you can use the `getDatabaseSchema()`
method.

#### `getGraphQlSchema(): Promise<string>`

Return the generated GraphQL schema.

```js
// server: TestxServer
await server.bootstrap();
console.log(await server.getGraphQlSchema());
```

```graphql
type Item {
  id: ID!
  name: String!
}

input ItemInput {
  name: String!
}

input ItemFilter {
  id: ID
  name: String
}

type Query {
  findItems(fields: ItemFilter!): [Item!]!
  findAllItems: [Item!]!
}

type Mutation {
  createItem(input: ItemInput!): Item!
  updateItem(id: ID!, input: ItemInput!): Item!
  deleteItem(id: ID!): ID!
}

type Subscription {
  newItem: Item!
  updatedItem: Item!
  deletedItem: ID!
}
```

#### `getDatabaseSchema(): Promise<{[table: string]: string[]}>`

Return the generated database schema.

```js
// server: TestxServer
await server.bootstrap();
console.log(await server.getDatabaseSchema());
```

```js
{
  item: ["id", "name", "created_at", "updated_at"];
}
```

#### `getQueries(): Promise<{[query: string]: string}>`

Return ready-to-use client queries.

```js
// server: TestxServer
await server.bootstrap();
console.log((await server.getQueries()).findAllItems);
```

```graphql
query findAllItems {
  findAllItems {
    ...ItemFields
  }
}

fragment ItemFields on Item {
  id
  name
}
```

#### `getMutations(): Promise<{[query: string]: string}>`

Return ready-to-use client mutations like for `getQueries()`.

#### `getSubscriptions(): Promise<{[query: string]: string}>`

Return ready-to-use client subscriptions like for `getQueries()`.

### `TestxController`

Controls the `TestxServer` remotely using the `TestxDirector`.

The `TestxController` is used in combination with the `TestxDirector` in the
[Karma example](./example/karma) in order to start/stop the server, and clean
the database from the browser.

```
 TestxDirector.start()     | Browser
          |
POST / { name: "start" }
          |
    TestxController        |
          |                | Node.js
  TestxServer.start()      |
```

```js
import { TestxServer, TestxController } from "graphql-testx";

// server: TestxServer
const controller = new TestxController(server);
await controller.start();

console.log(`Controller running on ${await controller.httUrl()}`);

await controller.close();
```

#### `start(port?: number): Promise<void>`

Start the `TestxController` API to a random available port on localhost or to
the passed port.

#### `httpUrl(): Promise<string>`

Return the http url to the `TestxController` API.

#### `stop(): Promise<void>`

Stop and close the `TestxController` and the `TestxServer`

### `TestxDirector`

Client API for the `TestxController` that implements all `TestxServer` methods.

Is used in combination wit the `TestxController`.

```ts
import { TestxDirector } from "graphql-testx/director";

// controller: TestxController
// controllerHttpUrl = await controller.httpUrl();
const director = new TestxDirector(controllerHttpUrl);

await director.start(); // start the TestxServer
await director.httUrl(); // TestxServer http url
// ... all others TestxServer methods
await director.close(); // close the TestxServer
```

---
_Source: https://npm.io/package/graphql-testx · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
