Jasmine 配置选项 #
配置概览 #
Jasmine 提供了多种配置方式来自定义测试行为:
text
┌─────────────────────────────────────────────────────────────┐
│ 配置方式概览 │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ jasmine.json │ │ 命令行参数 │ │ 代码配置 │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ 报告器配置 │ │ 随机测试 │ │ 超时设置 │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
jasmine.json 配置文件 #
基本结构 #
json
{
"spec_dir": "spec",
"spec_files": [
"**/*[sS]pec.?(m)js"
],
"helpers": [
"helpers/**/*.?(m)js"
],
"stopSpecOnExpectationFailure": false,
"random": true,
"seed": 12345
}
配置选项详解 #
json
{
"spec_dir": "spec",
"spec_files": [
"**/*[sS]pec.js",
"**/*[sS]pec.ts"
],
"helpers": [
"helpers/**/*.js",
"helpers/**/*.ts"
],
"stopSpecOnExpectationFailure": false,
"stopOnSpecFailure": false,
"failFast": false,
"random": true,
"seed": null,
"verboseDeprecations": true,
"oneFailurePerSpec": false,
"hideDisabled": false,
"reporters": [
{
"name": "console"
}
]
}
配置文件位置 #
text
project/
├── spec/
│ └── support/
│ └── jasmine.json # 默认位置
├── package.json
└── src/
初始化配置 #
使用 jasmine init #
bash
# 初始化 Jasmine
npx jasmine init
# 创建默认配置文件
# spec/support/jasmine.json
手动创建配置 #
bash
# 创建目录结构
mkdir -p spec/support
# 创建配置文件
touch spec/support/jasmine.json
命令行选项 #
基本命令 #
bash
# 运行所有测试
jasmine
# 运行特定文件
jasmine spec/my-spec.js
# 使用特定配置文件
jasmine --config=path/to/jasmine.json
# 指定测试目录
jasmine --spec-dir=tests
# 指定测试文件模式
jasmine --spec-files="**/*.test.js"
常用选项 #
bash
# 随机测试顺序
jasmine --random=true
# 指定随机种子
jasmine --seed=12345
# 禁用随机
jasmine --random=false
# 首次失败后停止
jasmine --stop-on-failure=true
# 显示帮助
jasmine --help
# 显示版本
jasmine --version
过滤测试 #
bash
# 运行匹配名称的测试
jasmine --filter="should add numbers"
# 使用正则表达式
jasmine --filter="/Calculator/"
报告器选项 #
bash
# 使用 HTML 报告器
jasmine --reporter=html
# 使用自定义报告器
jasmine --reporter=./custom-reporter.js
代码配置 #
使用 Jasmine 对象 #
javascript
const Jasmine = require('jasmine');
const jasmine = new Jasmine();
jasmine.loadConfigFile('spec/support/jasmine.json');
jasmine.loadConfig({
spec_dir: 'spec',
spec_files: ['**/*[sS]pec.js'],
helpers: ['helpers/**/*.js'],
random: true
});
jasmine.execute();
jasmine.execute(['spec/my-spec.js'], 'should add numbers');
配置环境 #
javascript
const Jasmine = require('jasmine');
const jasmine = new Jasmine();
jasmine.configureDefaultReporter({
showColors: true,
print: function() {
process.stdout.write(arguments[0]);
}
});
jasmine.addReporter(new CustomReporter());
jasmine.clearReporters();
jasmine.addReporter(new MyReporter());
报告器配置 #
默认控制台报告器 #
javascript
jasmine.configureDefaultReporter({
showColors: true,
print: function(message) {
console.log(message);
},
stackFilter: function(stack) {
return stack.split('\n').slice(0, 5).join('\n');
}
});
自定义报告器 #
javascript
const myReporter = {
jasmineStarted: function(suiteInfo) {
console.log('Running suite with ' + suiteInfo.totalSpecsDefined + ' specs');
},
suiteStarted: function(result) {
console.log('Suite started: ' + result.description);
},
specStarted: function(result) {
console.log('Spec started: ' + result.description);
},
specDone: function(result) {
console.log('Spec: ' + result.description + ' was ' + result.status);
for (let i = 0; i < result.failedExpectations.length; i++) {
console.log('Failure: ' + result.failedExpectations[i].message);
}
},
suiteDone: function(result) {
console.log('Suite: ' + result.description + ' was ' + result.status);
},
jasmineDone: function(result) {
console.log('Finished suite: ' + result.overallStatus);
}
};
jasmine.addReporter(myReporter);
使用第三方报告器 #
javascript
const JUnitXmlReporter = require('jasmine-reporters').JUnitXmlReporter;
jasmine.addReporter(new JUnitXmlReporter({
savePath: 'reports',
consolidateAll: true,
filePrefix: 'junit'
}));
HTML 报告器 #
javascript
const HTMLReporter = require('jasmine-pretty-html-reporter').HTMLReporter;
jasmine.addReporter(new HTMLReporter({
outputPath: 'reports',
screenshotPath: './screenshots',
writeReportEachSpec: true
}));
随机测试 #
启用随机测试 #
json
{
"random": true
}
bash
jasmine --random=true
使用种子重现测试顺序 #
json
{
"random": true,
"seed": 12345
}
bash
jasmine --random=true --seed=12345
代码中配置随机 #
javascript
describe('random tests', function() {
it('should work in random order', function() {
});
});
jasmine.getEnv().configure({
random: true,
seed: 12345
});
超时设置 #
全局超时 #
javascript
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
在配置文件中设置 #
json
{
"defaultTimeoutInterval": 10000
}
单个测试超时 #
javascript
describe('timeout', function() {
it('should complete within timeout', function(done) {
asyncFunction(function() {
done();
});
}, 5000);
it('async/await with timeout', async function() {
const result = await longRunningOperation();
expect(result).toBeDefined();
}, 10000);
});
钩子函数超时 #
javascript
describe('hook timeout', function() {
beforeEach(function(done) {
setupDatabase(function() {
done();
});
}, 10000);
it('should work', function() {
expect(true).toBe(true);
});
});
测试文件匹配 #
基本模式 #
json
{
"spec_files": [
"**/*[sS]pec.js"
]
}
多种模式 #
json
{
"spec_files": [
"**/*[sS]pec.js",
"**/*[tT]est.js",
"**/__tests__/**/*.js"
]
}
排除文件 #
json
{
"spec_files": [
"**/*[sS]pec.js",
"!**/node_modules/**",
"!**/vendor/**"
]
}
辅助文件 #
配置辅助文件 #
json
{
"helpers": [
"helpers/**/*.js"
]
}
辅助文件示例 #
javascript
// spec/helpers/global-setup.js
beforeEach(function() {
jasmine.addMatchers({
toBeEven: function() {
return {
compare: function(actual) {
return {
pass: actual % 2 === 0,
message: `Expected ${actual} ${actual % 2 === 0 ? 'not ' : ''}to be even`
};
}
};
}
});
});
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
javascript
// spec/helpers/mock-setup.js
beforeEach(function() {
this.mockApi = jasmine.createSpyObj('Api', ['get', 'post']);
});
afterEach(function() {
});
环境配置 #
Node.js 环境 #
javascript
const Jasmine = require('jasmine');
const jasmine = new Jasmine();
jasmine.loadConfigFile('spec/support/jasmine.json');
jasmine.execute();
浏览器环境 #
html
<!DOCTYPE html>
<html>
<head>
<title>Jasmine Tests</title>
<link rel="stylesheet" href="jasmine.css">
</head>
<body>
<script src="jasmine.js"></script>
<script src="jasmine-html.js"></script>
<script src="boot0.js"></script>
<script src="boot1.js"></script>
<script src="spec/my-spec.js"></script>
</body>
</html>
TypeScript 支持 #
json
{
"spec_files": [
"**/*[sS]pec.ts"
],
"helpers": [
"helpers/**/*.ts"
]
}
javascript
// spec/helpers/ts-setup.js
require('ts-node').register({
transpileOnly: true
});
完整配置示例 #
项目配置 #
json
{
"spec_dir": "spec",
"spec_files": [
"**/*[sS]pec.?(m)js",
"**/*[tT]est.?(m)js"
],
"helpers": [
"helpers/**/*.?(m)js"
],
"stopSpecOnExpectationFailure": false,
"stopOnSpecFailure": false,
"random": true,
"seed": null,
"verboseDeprecations": true,
"defaultTimeoutInterval": 5000
}
package.json 脚本 #
json
{
"scripts": {
"test": "jasmine",
"test:watch": "nodemon --exec jasmine",
"test:coverage": "nyc jasmine",
"test:ci": "jasmine --reporter=junit --output=reports"
}
}
完整设置脚本 #
javascript
// spec/support/jasmine-setup.js
const Jasmine = require('jasmine');
const reporters = require('jasmine-reporters');
const jasmine = new Jasmine();
jasmine.loadConfig({
spec_dir: 'spec',
spec_files: ['**/*[sS]pec.js'],
helpers: ['helpers/**/*.js'],
random: true,
stopOnSpecFailure: false
});
jasmine.addReporter(new reporters.TerminalReporter({
color: true,
showStack: true
}));
jasmine.addReporter(new reporters.JUnitXmlReporter({
savePath: 'reports',
consolidateAll: true,
filePrefix: 'test-results'
}));
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
module.exports = jasmine;
javascript
// spec/support/env.js
beforeAll(function() {
process.env.NODE_ENV = 'test';
});
afterAll(function() {
process.env.NODE_ENV = 'development';
});
配置对照表 #
| 选项 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| spec_dir | string | ‘spec’ | 测试文件目录 |
| spec_files | array | [‘**/*[sS]pec.js’] | 测试文件模式 |
| helpers | array | [] | 辅助文件模式 |
| random | boolean | true | 是否随机测试顺序 |
| seed | number | null | 随机种子 |
| stopSpecOnExpectationFailure | boolean | false | 失败时停止当前测试 |
| stopOnSpecFailure | boolean | false | 失败时停止所有测试 |
| failFast | boolean | false | 快速失败模式 |
| oneFailurePerSpec | boolean | false | 每个 spec 只报告一个失败 |
| hideDisabled | boolean | false | 隐藏禁用的测试 |
| defaultTimeoutInterval | number | 5000 | 默认超时时间(毫秒) |
下一步 #
现在你已经掌握了 Jasmine 的配置选项,接下来学习 高级特性 了解更多高级功能!
最后更新:2026-03-28