首页 > 解决方案 > Cover Material-UI MakeStyles with Jest

问题描述

Every time I test my Material UI files, Jest complains because I mock makeStyles and says that I didn't cover the entire file.

So, it shows me on the coverage file:

Jest test results

My test file has this:

jest.mock('@material-ui/styles', () => ({
  ...jest.requireActual('@material-ui/styles'),
  makeStyles: () => () => ({}),
}))

How can I mock makeStyles in a way that Jest stops complaining about that and making my coverage reports "false negatives"?

标签: reactjsunit-testingjestjsmaterial-ui

解决方案


(What exactly do you mean with "Jest complains"? If I understand you right, it's all about the coverage report, right? I guess that the tests itself are working.)

Your production code uses callbacks like theme => ({ cardContent, divider, spacer }) as argument to makeStyles(), but your mockup does ignore those arguments and that way hides the callbacks from every test - i.e. there will be no test which actually does something with the callbacks and their results.

The coverage report is right - you're missing parts of the tested files. The following might increase the rating of your code coverage, but without any more logic you could end up with some "false positives", I guess...

jest.mock('@material-ui/styles', () => ({
  ...jest.requireActual('@material-ui/styles'),
  makeStyles: cb => () => cb({ spacing: () => 0 }),
}))

推荐阅读