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

余生颓废 提交于 2021-02-05 11:57:47

问题


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.


回答1:


It's impossible to mock getData as myapp.getData. module.exports.getData = getData doesn't serve a good purpose for testing because it allows to mock getData only if it's used everywhere as exports.getData() instead of getData(), which is impractical.

data needs to be mocked in a module it's defined. Then all modules that depend on it should be re-imported per test in order to be affected by a mock. jest.isolateModules or jest.resetModules can be used in conjunction with require to provide test-specific module mocks.

beforeEach(() => {
  jest.resetModules();
});

it('should return 2 lists', async () => {
  jest.mock('.../data', () => [...]);
  const myapp = require('.../app');

  const res = await request(myapp)
  ...
});


来源:https://stackoverflow.com/questions/63762896/whats-the-best-way-to-test-express-js-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!