Search code examples
javascriptunit-testingjestjs

How to match inner text using Jest matcher


I have some object that I am trying to match using to expect(process).toHaveBeenCalledWith({})

There is a process which appends a date when a document in passed in to it. That process is able to get the full document when given the start of it's name. So passing process('my-doc') I could get back my-doc-2021-01-22.pdf. I want to write a test to mock that function to use to have been called. My call is identical but with filenames doc1 and doc2. However, my call fails when I use to expect(process).toHaveBeenCalledWith({})because my objects don't match exactly after the transformation by some method in process(). How can I say expect(...).toContain('doc1) ?

The resulting object after process is like this:


    const message = {
                     documents: [
                     {
                      filename: "doc1-2022-05-08",
                      content: 'text1',
                     },
                     {
                      filename:  doc2-2022-03-22,
                      content:'text2',
                     },

                 }



Solution

  • To test that your process function has been called with the correct filenames, you can use the expect(...).toHaveBeenCalledWith(...) method along with a custom matcher.

        expect(process).toHaveBeenCalledWith(
          expect.objectContaining({
            documents: expect.arrayContaining([
              expect.objectContaining({
                filename: expect.stringMatching(/doc1-\d{4}-\d{2}-\d{2}/),
              }),
              expect.objectContaining({
                filename: expect.stringMatching(/doc2-\d{4}-\d{2}-\d{2}/),
              }),
            ]),
          }),