[ PART 2 ] Creating a Twitter clone with GraphQL, Knex, Typescript, and React ( Setup Tests )
ips-coding-challenge
Posted on January 6, 2021
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
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"
},
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
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()
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
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)
}
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')
})
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
Posted on January 6, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
January 7, 2021
January 6, 2021