如何强制jest在root lvl __snapshots__文件夹中输出快照?

时间:2018-05-06 14:18:25

标签: testing jest

我今天遇到了小问题,我的文件夹结构遵循这个惯例

components/
   Paragraph/
     index.js
     style.js
     test.js

当我运行jest快照测试时,它会在每个组件文件夹中生成它们,即

components/
   Paragraph/
     __snapshots__
     index.js
     style.js
     test.js

有没有办法强制jest将所有快照放在root lvl __snapshot__文件夹中?所以最终输出看起来更像这个

__snapshots__
   // All snapshots here?
components/
   Paragraph/
     index.js
     style.js
     test.js

1 个答案:

答案 0 :(得分:0)

package.json 中(或在jest.config.js中,如果使用的话)将路径添加到snapshotResolver文件

"jest": {
    "snapshotResolver": "./snapshotResolver.js"
}

在根项目中,使用以下代码创建snapshotResolver.js文件:

const path = require('path')

const rootDir = path.resolve(__dirname, '..')

module.exports = {
  testPathForConsistencyCheck: 'some/__tests__/example.test.js',

  /** resolves from test to snapshot path */
  resolveSnapshotPath: (testPath, snapshotExtension) => {
    return testPath.replace('src/', '__snapshots__/') + snapshotExtension
  },

  /** resolves from snapshot to test path */
  resolveTestPath: (snapshotFilePath, snapshotExtension) => {
    return snapshotFilePath
      .replace('__snapshots__/', 'src/')
      .slice(0, -snapshotExtension.length)
  },
}

https://gist.github.com/prescottprue/5ece5e173bcfba7ed86dae6a91444451