使用 npm 安装 Jasmine:
npm install --save-dev jasmine
初始化 Jasmine 配置:
npx jasmine init
基础测试
创建一个 example.spec.js
文件:
describe("A suite", function() {
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
});
运行测试:
npx jasmine
异步测试
describe("Async suite", function() {
it("should support async execution of test preparation and expectations", function(done) {
setTimeout(function() {
expect(true).toBe(true);
done();
}, 1000);
});
});
使用 Mock 和 Spies
describe("A spy", function() {
let foo, bar = null;
beforeEach(function() {
foo = {
setBar: function(value) {
bar = value;
}
};
spyOn(foo, 'setBar');
foo.setBar(123);
});
it("tracks that the spy was called", function() {
expect(foo.setBar).toHaveBeenCalled();
});
it("tracks all the arguments of its calls", function() {
expect(foo.setBar).toHaveBeenCalledWith(123);
});
});
钩子示例
describe("Hooks", function() {
beforeAll(function() {
// 在所有测试用例之前运行一次
});
afterAll(function() {
// 在所有测试用例之后运行一次
});
beforeEach(function() {
// 在每个测试用例之前运行
});
afterEach(function() {
// 在每个测试用例之后运行
});
it("should run this test", function() {
// 测试代码
});
});
describe(description, function):定义一个测试套件,将相关的测试用例分组。
describe("A suite", function() {
// tests
});
it(description, function):定义一个测试用例。
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
expect(actual):断言一个值,与各种匹配器结合使用。
expect(actual).toBe(expected);
beforeAll(function):在所有测试用例之前运行一次。
beforeAll(function() {
// setup code
});
afterAll(function):在所有测试用例之后运行一次。
afterAll(function() {
// teardown code
});
beforeEach(function):在每个测试用例之前运行。
beforeEach(function() {
// setup code
});
afterEach(function):在每个测试用例之后运行。
afterEach(function() {
// teardown code
});
spyOn(object, 'method'):创建一个 spy 来跟踪对象方法的调用情况。
spyOn(foo, 'setBar');
自定义匹配器
Jasmine 允许创建自定义匹配器以增强测试断言功能:
beforeEach(function() {
jasmine.addMatchers({
toBeDivisibleBy: function() {
return {
compare: function(actual, expected) {
const result = {};
result.pass = (actual % expected) === 0;
if (result.pass) {
result.message = `Expected ${actual} to be divisible by ${expected}`;
} else {
result.message = `Expected ${actual} to be divisible by ${expected}, but it was not`;
}
return result;
}
};
}
});
});
it("is divisible by 3", function() {
expect(9).toBeDivisibleBy(3);
});
异步代码测试
除了回调函数,Jasmine 还支持使用 async/await 进行异步测试:
describe("Async suite with async/await", function() {
it("should support async/await", async function() {
const result = await new Promise(resolve => {
setTimeout(() => resolve(true), 1000);
});
expect(result).toBe(true);
});
});