DEV Community

Cover image for [ PART 2 ] Creating a Twitter clone with GraphQL, Knex, Typescript, and React ( Setup Tests )
ips-coding-challenge
ips-coding-challenge

Posted on • Updated on

[ PART 2 ] Creating a Twitter clone with GraphQL, Knex, Typescript, and React ( Setup Tests )

Github Repository

Setting up the tests

I will use jest for testing and this will be a first for me being more used to mocha + chai. I could change to ava eventually to if I don't like jest ;).

The jest library being already installed, I'm going to install ts-jest since I use typescript and it's apparently the easiest way to set up everything.

yarn add -D ts-jest
yarn ts-jest config:init
Enter fullscreen mode Exit fullscreen mode

package.json

"scripts": {
    "dev": "nodemon src/index.ts --exec ts-node",
    "build": "shx rm -rf dist/ && tsc -p .",
    "start": "node dist/src/index.js",
    "test": "jest"
},
Enter fullscreen mode Exit fullscreen mode

Since I'm going to reuse my server for testing, I'm going to excract it into another file.

src/server.ts

import 'reflect-metadata'
import { ApolloServer } from 'apollo-server'
import { buildSchema } from 'type-graphql'
import AuthResolver from './resolvers/AuthResolver'

const createServer = async () => {
  return new ApolloServer({
    schema: await buildSchema({
      resolvers: [AuthResolver],
    }),
  })
}

export default createServer

Enter fullscreen mode Exit fullscreen mode

And as a result, my index.ts file becomes

src/index.ts

import dotenv from 'dotenv'
import path from 'path'
import createServer from './server'
dotenv.config({
  path: path.join(__dirname, `../.env.${process.env.NODE_ENV}`),
})

const main = async () => {
  const server = await createServer()

  server.listen().then(({ port }) => {
    console.log(`Listening on port ${port}`)
  })
}
main()

Enter fullscreen mode Exit fullscreen mode

In my src directory, I create a tests directory and 2 files, setup.ts and auth.test.ts.

I will also need the apollo-server-testing library

yarn add -D apollo-server-testing
Enter fullscreen mode Exit fullscreen mode

src/tests/setup.ts

import createServer from '../server'
import { createTestClient } from 'apollo-server-testing'

export const testClient = async () => {
  const server = await createServer()

  return createTestClient(server)
}

Enter fullscreen mode Exit fullscreen mode

src/tests/auth.test.ts

import { gql } from 'apollo-server'
import { testClient } from './setup'

const TEST = gql`
  query {
    me
  }
`

test('it should show hello', async () => {
  const { query } = await testClient()

  const res = await query({ query: TEST })

  expect(res.data.me).toEqual('Hello')
})

Enter fullscreen mode Exit fullscreen mode

Test result

Looks like it's working, we can finally start having fun :D

The next part will be about Authentication ;).

Have a nice day! ;)

You learned 2-3 things and want to buy me a coffee ;)?
https://www.buymeacoffee.com/ipscoding

Top comments (0)