Shared utils functions for testing with Jest

前端 未结 2 1733
夕颜
夕颜 2021-01-01 09:07

I have some utils functions that I\'m using among various Jest tests, for example a function like this, for mocking a fetch response:



        
2条回答
  •  -上瘾入骨i
    2021-01-01 09:48

    Another approach is by having a test directory and moving helpers on it.

    src/
      components/
      utils/
      ...
    test/
      testHelpers.js
    

    Then on the test:

    // src/components/MyComponent.spec.js
    import { helperFn } from '../../test/testHelpers';
    

    Benefits:

    • Be explicit of where the function is coming from
    • Separate helpers that need to be tested from those that do not ¹

    Drawbacks:

    • The test directory might look silly by containing just a helper file
    • AFAIK this approach is no where specified on official documentation

    Looks like GitLab is implementing this approach on their RoR project.

    ¹ no matter which approach you take, please don't test the test helpers. If the helper fails then your test must fail too. Otherwise your helper is not helping at all.

提交回复
热议问题