Expect — Assert a Partial Object Match (in Jest’s Expect)

Testing objects and asserting their equality can be tricky. For example, in integration tests where you’re sending HTTP requests to a server and receiving responses back. You may want to assert a subset of response headers to match a given expectation.

You may not be in control of the response headers because the framework adds some headers describing the response. That’s where partial object assertions come in handy.

This tutorial shows you how to assert partial object matches in Jest’s expect assertion library.

Expect Series Overview

  1. Assert a Partial Object Match (in Jest’s Expect)

Assert a Partial Object Match in Expect

Expect provides an expect(actual).toMatchObject(expectedObject) method. This method checks that the actual object contains all top-level and nested properties of the expectedObject.

The .toMatchObject assertion requires all properties to have the same value in the actual and expected objects.

Here’s a simple example:

// ✅ SUCCESSFUL assertion
const tutorial = {  
  tags: ['nodejs', 'expect'],
  title: 'Expect — Assert a Partial Object Match (in Jest’s Expect)',
  author: {
    name: 'Marcus'
  }
}

expect(tutorial).toMatchObject({  
  tags: ['nodejs', 'expect'],
  author: {
    name: 'Marcus'
  }
})

Notice the tags array containing the two tags. If your expected object contains a given property, it must match or contain all values of the actual value. In the following example, the expected tags don’t match the actual tags resulting in a failing assertion:

// ❌ FAILING assertion
const tutorial = {  
  tags: ['nodejs', 'expect'],
  title: 'Expect — Assert a Partial Object Match (in Jest’s Expect)',
  author: {
    name: 'Marcus'
  }
}

expect(tutorial).toMatchObject({  
  tags: ['expect'],
  author: {
    name: 'Marcus'
  }
})

The assertion above fails because the expected tags array contains only one of the required two string values.

Practical Example: Expect HTTP Request Headers

Here’s an advanced example of how you can use the .toMatchObject() assertion in your tests. The example sends an HTTP request with a custom header into a Koa server and echos the request headers. The assertion then expects the specific request header that you sent:

// import `expect` if you’re using it outside of Jest
const Koa = require('koa')  
const expect = require('expect')  
const Supertest = require('supertest')

const app = new Koa().use(ctx => {  
  ctx.body = ctx.headers
})

const response = await Supertest(app.callback())  
  .get('/')
  .set('x-futurestudio', 'is-nice')
  .expect(200)

expect(response.body).toMatchObject({  
  'x-futurestudio': 'is-nice'
})

Enjoy!


Mentioned Ressources

Explore the Library

Find interesting tutorials and solutions for your problems.