5

I would like to add React Testing Library to a project that uses mocha and chai for unit tests. I am a bit stumped when it comes to writing assertions, most examples make use of jest and jest-dom. I am really keen to use assertions like toBeInTheDocument or toHaveTextContent

I am wondering if there is a chai plugin that is a suitable replacement for jest-dom? or what alternative solutions you have found for using React Testing Library with mocha and chai?

76484
  • 8,498
  • 3
  • 19
  • 30
Frederick Duffield
  • 123
  • 1
  • 1
  • 8

2 Answers2

4

chai-dom is an alternative. It's a plugin that provides a subset of assertions on the dom. Unfortunately, the assertions are not as declarative or extensive as jest-dom.

Using chai-dom, we'd use exist in place of toBeInTheDocument and text in place of toHaveTextContent.

Derek Yu
  • 41
  • 4
0

You can extend matchers in your test configuration file to use Jest's ones or any others.

  1. Install the @testing-library/jest-dom which contains the matchers

  2. Be sure you are indicating a configuration file for mocha, this is one of the ways to do it through .mocharc.js

    // .mocharc.js
    
    module.exports = {  
      ...  
      require: ['test.config.js']  
    };  
    
  3. Now in add this into your test.config.js file, not runtime config which is for different purposes.

    // test.config.js
    
    // Imports Jest's matchers  
    const extendExpectMatchers = require('@testing-library/jest-dom/matchers');  
    // Imports expects  
    const expect = require('expect');  
    // Extend expects with @testing-library/jest-dom  
    expect.extend(extendExpectMatchers);  
    

Then use it as usual in your tests

expect(screen.getByText('Whatever')).toBeInTheDocument();
Olek
  • 106
  • 6