Reading Artists
We have implemented a POST endpoint for creating Artist records, but without the ability to handle GET requests, our app has no way to retrieve those records.
Lets make a new test file called src/tests/artist-read.test.js:
beforeEach
Like our last test file, we are using the beforeEach hook to establish a connection to the database before each test.
Unlike the other tests, for these tests we also need to have some data in the Artist table before the tests run. This is done by the Promise.all() method, which will resolve an array of promises. In this case an array of db.query() functions.
After these promises have resolved, we are querying the database again to get all the artists, and storing them in a variable called artists.
The artists variable is declared as a let outside of the beforeEach so that it is in the same scope as the tests.
The Test
The test itself is fairly straightforward. It sends a GET request to /artists and expects a 200 response.
It then expects the response body to be an array containing 3 elements.
Finally, it checks if each item in the response body matches an item in the artists array.
Challenge
To get started passing this test, you will need to:
-
Run the test and confirm that it fails. It will complain that it received a
404status when it expected a201. -
Start by writing a
readfunction in yoursrc/controllers/artist.jsfile. For now just have it return a200status code in the response. -
Add a
router.get('/', artistController.read)route to yoursrc/routes/artist.js. If you run your test again, it will still fail, but this time it will be because we aren't returning anything in theresponse body. Progress! -
Now that we know the controller function is receiving requests, get a connection to the database the same way you did for the
createcontroller. -
Use
db.query()toSELECTall the artists from theArtisttable. It will return aresponseobject with arowsproperty. ThebeforeEachhook in the tests provides an example on how to use destructuring syntax to extract the data we want from the return values. -
Change your controller to return the artists to the user. Run your tests again to see if they pass.
You can find a solution to this challenge here