dimanche 6 septembre 2020

What's the best way to test express.js API

I'm new in API testing with JavaScript. I've found many solution for testing REST APIs, but not sure what's the best. Im using express.js in the backend and for the tests jest.

I've seen that I can test with jest, by mocking the function or that I can also mock the API directly.

I've a data.js where the object is stored:

let data = [
{
    id: 0,
    name: "empty shopppinglist",
    location: "",
    targetDate: "",
    priority: "",
    isFinished: false,
    items: ["vodka"
    ]
}
]
module.exports = data

Then in the Backend Folder I have this to provide the endpoint and read / return the file:

function getData(){
  let shoppingLists = data
  return shoppingLists
}
module.exports.getData = getData
let shoppingLists = data



app.get('/api/shoppingLists', (req, res) => {
   const listsWithoutItems = getData().map(({ items, ...rest }) => rest)
   res.status(200).send(listsWithoutItems)
})

I'm here also not sure, if I can move the app.get call to a function.

In my test, I'd like to test the behaviour of the API, so if invalid data, that I will get an error 500 etc.. For this I've tried with this test:

describe('Get Endpoint for all Lists', () => {

it('should return 2 lists', async () => {
    myapp.getData = jest.fn(() => [
        {
            "id": 0,
            "name": "filled shopping list",
            "location": "lidl",
            "targetDate": "22.03.1986",
            "priority": "1",
            "isFinished": false,
            "items": ["vanille"
            ]
        }
    ])

    const res = await request(myapp)
        .get('/api/shoppingLists')
    expect(res.statusCode).toEqual(200)
    expect(res.body).toHaveProperty('2')
})
})

Unfortunately, I always get the original entry from data.js and not the mocked result. And by searching for documentation, I've also seen, that I can mock the whole app.js where my API is defined. But now I'm not sure what is the better way to do that.

Aucun commentaire:

Enregistrer un commentaire