The task to set up Jest and React Testing library for TDD using Gatsby is an easy one.Its tricky as i planned to use Typescripts in my test.
Firstly , i installed jest, babel-jest and babel-preset-gatsby ensuring the presence of babel preset(s) which can be used internally for Gatsby site.
npm install –save-dev jest babel-jest babel-preset-gatsby identity-obj-proxy tslint-react @types/jest
Configure Jest for checking its working with Gatsby
As Gatsby has its own babel configuration so we have to manually tell jest to use babel-jest. the gatsby website tells to create jest.config.js file. look at the code below
Now i will write my first test and run it. I like TDD because it is fast. We can write test before writing code. A test should fail at the beginning Read this up. Now i will create a folder named __tests__ in my root folder of project. Then i will create a file named test.spec.tsx and paste this code in it.
tests/test.spec.tsx
import React from "react"
import { render } from "@testing-library/react"
// You have to write data-testid
const Title = () => <h1 data-testid="hero-title">Gatsby is awesome!</h1>
test("Displays the correct title", () => {
const { getByTestId } = render(<Title />)
// Assertion
expect(getByTestId("hero-title")).toHaveTextContent("Gatsby is awesome!")
// --> Test will pass
})
Run commands like Yarn or npm install if you get errors like.
Cannot find module 'react' from 'test.spec.tsx'
> 1 | import React from "react"
YAAYYY WE ACCOMPLISHED UNIT TESTING WITH TYPESCRIPT AND GATSBY AND JEST AND REACT TESTING LIBRARY
I am very happy with this . I will just start out Typescript with React so this was a great deal of learning for me. I’ll put up more post about writing real code using TDD. stay tuned
The most popular stack these days is GraphQl and Typescript. I used Vanilla JavaScript in one of my recent projects but I have used Typescript many times. I never used this but I followed a tutorial which helped me a lot so I thought of guiding others too. Before starting let us see:
Why GraphQL, TypeScript and PostgreSQL ?:
The description in our API is provided by GraphQL. It helps in understanding the needs of the clients and helps us while dealing with large amounts of data, as one can have all the data by running only one query.
Typescript is used as a superset of javascript. When javascript code takes more compliance time and becomes messier to reuse or maintain we can use typescript instead.
PostgreSQL is based on personal preference and is open-source. you can view the following link for more details.
Webpack: Webpack can be used to compile JavaScript modules, node.js do not accept files like .gql or .graphql, that’s why we use Webpack. install the following
import express, { Application } from 'express';
import { ApolloServer , Config } from 'apollo-server-express';
const app: Application = express();
const schema = `
type User{
name: String
}
type Query {
user:User
}
`
const config : Config = {
typeDefs:schema,
resolvers : {
Query:{
user:(parent,args,ctx)=>{
return { name:"WOnder"}
}
}
},
introspection: true,//these lines are required to use the gui
playground: true,// of playground
}
const server : ApolloServer = new ApolloServer(config);
server.applyMiddleware({
app,
path: '/graphql'
});
app.listen(3000,()=>{
console.log("We are running on http://localhost:3000/graphql")
})
Server config
we will use, Executable schema from Graphql-tools. It allows us to generate GraphQLSchema and allow us to join the types or resolvers from a large number of files.
src/index.ts
...
const config : Config = {
schema:schema,// schema definition from schema/index.ts
introspection: true,//these lines are required to use
playground: true,// playground
}
const server : ApolloServer = new ApolloServer(config);
server.applyMiddleware({
app,
path: '/graphql'
});
...
schema/index.ts
import { makeExecutableSchema} from 'graphql-tools';
import schema from './graphql/schema.gql';
import {user,pet} from './resolvers';
const resolvers=[user,pet];
export default makeExecutableSchema({typeDefs:schema, resolvers: resolvers as any});
Database
Let’s see the database diagram including a registry of users and their pets.
Migration file
for the creation of a database in Postgres we use migration files of knew
import { Resolvers} from '../../__generated__/generated-types';
import {User,Pet} from '../../database/models';
import {UserInputError} from 'apollo-server-express';
interface assertion {
[key: string]:string | number ;
}
type StringIndexed<T> = T & assertion;
const resolvers : Resolvers ={
Query:{
users: async (parent,args,ctx)=>{
const users : User[] = await User.query();
return users;
},
user:async (parent,args,ctx)=>{
const user :User = await await User.query().findById(args.id);
return user;
},
},
User:{
pets:async (parent,args,ctx)=>{
const pets : Pet[] = await User.relatedQuery("pets").for(parent.id);
return pets;
}
},
Mutation:{
createUser:async (parent,args,ctx)=>{
let user : User;
try {
user = await User.query().insert({...args.user});
} catch (error) {
console.log(error);
throw new UserInputError('Email Invalido', {
invalidArgs: Object.keys(args),
});
}
return user;
},
updateUser:async (parent,{user:{id,...data}},ctx)=>{
let user : User = await User.query().patchAndFetchById(id,data);
return user;
},
deleteUser:async (parent,args,ctx)=>{
const deleted = await User.query().deleteById(args.id);
return "Succesfull deleted";
},
}
}
export default resolvers;
this will help to execute all the operations defined before
BONUS
two errors can be seen
It’s not bad to have errors, I prefer not to have errors, after this the first error is resolved by splitting knexfile.ts then put the required configuration for Knex in a separate file.
require('ts-node/register');
import config from './config';
module.exports= config["development"]
the second got resolved from importing from the schema and taking help from this useful post. now we should have to work on our own Graphql API
CONCLUSION
yay! now we have a GraphQL API. So we have learned generating types for Typescript from Graphql and solving issues. I hope you got help from this tutorial. I’ll be posting more soon. Give suggestions in the comment box. thankyou.