我正在努力提高我們的jest測驗的性能,其中包含4000多個測驗。 為了查看各個測驗的持續時間,我使用了--verbose標志。
是否有一個簡單的方法來發現運行時間最長的測驗,或者我必須滾動瀏覽整個輸出?
uj5u.com熱心網友回復:
你可以撰寫一個測驗報告,并將其添加到jest的reporters配置中。
./reporters/slow-test.js:
class JestSlowTestReporter {
constructor(globalConfig, options) {
this._globalConfig = globalConfig;
this._options = options;
this._slowTests = [] 。
}
onRunComplete(){
console.log()。
this._slowTests。 sort((a, b) => b.duration - a.duration) 。
var rootPathRegex = new RegExp(`^${process.cwd()}`) 。
var slowestTests = this._slowTests。 slice(0, this. _options.numTests || 10)。)
var slowTestTime = this._slowTestTime(slowestTests)。
var allTestTime = this._allTestTime()。
var percentTime = (slowTestTime / allTestTime) * 100。
console.log(
`Top ${slowestTests.length} 最慢的例子(${slowTestTime / 1000} 秒,`
` ${percentTime.toFixed(1)}總時間的%):`
);
for (var i = 0; i < slowestTests.length; i ) {
var duration = slowestTests[i].duration;
var fullName = slowestTests[i].fullName;
var filePath = slowestTests[i].filePath.replace(rootPathRegex, '. ' ) 。
console.log(`${fullName}`)。
console. log(` ${duration / 1000} seconds ${filePath}`) 。
}
console.log()。
}
onTestResult(test, testResult) {
for (var i = 0; i < testResult.testResults.length; i ) {
this._slowTests.push({
duration: testResult.testResults[i].duration。
fullName: testResult.testResults[i].fullName,
filePath: testResult.testFilePath,
});
}
}
_slowTestTime(slowestTests){
var slowTestTime = 0;
for (var i = 0; i < slowestTests.length; i ) {
slowTestTime = slowestTests[i].duration。
}
return slowTestTime。
}
_allTestTime() {
var allTestTime = 0;
for (var i = 0; i < this. _slowTests.length; i ) {
allTestTime = this._slowTests[i].duration。
}
return allTestTime;
}
}
module.exports = JestSlowTestReporter;
jest.config.js:
module.exports = {
preset: 'ts-jest/presets/js-with-ts'/span>,
reporters: ['default', ['<rootDir> /reporters/slow-test', { numTests: 3 }]]。
};
numTests: 3 引數意味著找到最慢的前3個測驗案例。
index.test.js:
describe('find top slowest test', ( ) => {
test('should 1', (done) => {
setTimeout(() => {
expect(1 1).toBe(2)。
done()。
}, 1000)。)
});
test('should 2', (done) => {
setTimeout(() => {
expect(1 1).toBe(2)。
done()。
}, 1200)。)
});
test('should 3', (done) => {
setTimeout(() => {
expect(1 1).toBe(2)。
done()。
}, 100)。)
});
});
測驗結果:
PASS examples/find-top-slowest-test/index.test.js
找到最慢的測驗
?應該 1 (1007 ms)
?應2 (1201 ms)
?應3 (103 ms)
Test Suites。1通過,1總計
測驗。 3通過,3總計
Snapshots。 0總計
時間。 3.588秒,估計4秒
Ran所有匹配//Usersdulin/workspace/github的測驗套件。 com/mrdulin/jest-v26-modelab/examples/find-top-slowest-test/index.test.
Top 3最慢的例子(2.311秒,100.0% of總時間)。
找到最慢的測驗應該2。
1.201秒 ./examples/find-top-slowest-test/index.test.js
找到最慢的測驗應該1。
1.007 seconds ./examples/find-top-slowest-test/index.test.js
找到最慢的測驗應該3。
0.103 seconds ./examples/find-top-slowest-test/index.test.js
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/310296.html
標籤:
