Notes Used to Craft this Lesson
What about testing a list of items? For this, we have our posts.index that returns an array of 3 different posts.
export default class PostsController { // ... async index() { return [ { id: 1, title: 'My first post', summary: 'Lorem ipsum dolor sit amet, consectetur ...', }, { id: 2, title: 'My second post', summary: 'Lorem ipsum dolor sit amet, consectetur ...', }, { id: 3, title: 'My third post', summary: 'Lorem ipsum dolor sit amet, consectetur ...', }, ] } // ... }Copied!
- app
- controllers
- posts_controller.ts
We'll test that this should "fetch a list of posts."
test("fetch a list of posts", async ({ client, assert, route }) => { const response = await client.get(route("posts.index")); response.assertOk(); });Copied!
Beyond asserting our 'ok' response, we may also want to confirm that we received an array from our body. For this, we can grab the actual response body via response.body(), then utilize the isArray assertion to confirm it's an array.
test("fetch a list of posts", async ({ client, assert, route }) => { const response = await client.get(route("posts.index")); const body = response.body(); response.assertOk(); assert.isArray(body); });Copied!
Next, we may want to confirm the array of objects contains the properties we'd expect.
test("fetch a list of posts", async ({ client, assert, route }) => { const response = await client.get(route("posts.index")); const body = response.body(); response.assertOk(); assert.isArray(body); assert.properties(body.at(0), ["id", "title", "summary"]); });Copied!
Lastly, assertBodyContains also works great with arrays! So, we can use that to loosely confirm that the actual data we received is correct as well.
test("fetch a list of posts", async ({ client, assert, route }) => { const response = await client.get(route("posts.index")); const body = response.body(); response.assertOk(); assert.isArray(body); assert.properties(body.at(0), ["id", "title", "summary"]); response.assertBodyContains([ { id: 1, title: "My first post" }, { id: 2, title: "My second post" }, { id: 3, title: "My third post" }, ]); });Copied!