Search code examples
javascripttypescriptexpressjestjsts-jest

Testcases using jest with Typescript


My small testcases getting failed there are two files are include which are : index.js and index.test.js

please help me

These are my some api endpoints :

import express from 'express';
const app = express();

const port = 3000;

let data =  [{id: 1, name: "Atharva", accType: "Saving",email:"katharva2002@gmail.com", Data_Acc_created: new Date(), balance: 100, Nooftransaction: 0},
{id: 2, name: "Soham", accType: "Current",email:"soham2002@gmail.com", Data_Acc_created: new Date(), balance: 200, Nooftransaction: 2},
{id: 3, name: "Sujyot", accType: "Saving",email:"sujyot2002@gmail.com", Data_Acc_created: new Date(), balance: 300, Nooftransaction: 3}]
let transactionT = [{id: 1, transactiontime: new Date(), amount : 300}, {id:2, transactiontime: new Date(), amount:200}, {id:3,transactiontime: new Date(), amount : 888}];

app.use(express.json())
const dataLength = data.length;


//   get/getaccsummary -> givs account summary
app.get("/getaccsummary", (req: express.Request, res: express.Response)=>{
    console.log('/GET getaccsummary');
    res.json(data);
});

//   get/account/index -> gives account summary specific index
app.get("/account/:id",(req: express.Request, res: express.Response)=>{
    const accountid = Number(req.params.id)
    const getAccount = data.find((element)=>element.id === accountid)

    if(!getAccount){
        res.status(500).send("Account not Found");
    }else{
        res.json(getAccount);
    }
});

This is my testfile stored in test file

import request from 'supertest';
import app from "../index";

describe("GET /getaccsummary", () => {
    it('resopose ', async () => {
      const response = await request(app).get('/getaccsummary');
      expect(response.status).toBe(200);
      
    });
  });

The errors im getting:

> final-typescriptt@1.0.0 test
> jest

 FAIL  __test__/index.test.ts
  ● Test suite failed to run

    TypeError: (0 , express_1.default) is not a function

      2 | exports.__esModule = true;
      3 | var express_1 = require("express");
    > 4 | var app = (0, express_1["default"])();
        |                                    ^
      5 | var port = 3000;
      6 | var data = [{ id: 1, name: "Atharva", accType: "Saving", email: "katharva2002@gmail.com", Data_Acc_created: new Date(), balance: 100, Nooftransaction: 0 },
      7 |     { id: 2, name: "Soham", accType: "Current", email: "soham2002@gmail.com", Data_Acc_created: new Date(), balance: 200, Nooftransaction: 2 },
      at Object.<anonymous> (index.js:4:36)
      at Object.<anonymous> (__test__/index.test.ts:2:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        2.21 s
Ran all test suites

How do i write tests for GET request with correct testacases is there somthing im missing please let me know :)


Solution

  • just require the express again in your testfile.js . Then

    const app = express();