我熟悉RSpec,通过编写共享示例可以很容易地重用测试用例
shared_example_for 'a cute pet' do
it 'tests that the pet is a small' { expect(pet.size).to be_lesser_than(10) }
it 'tests that the pet can smile' { expect(pet.can_smile?).to be }
end
describe 'The Octocat' do
let(:pet) Octocat.new
it_behaves_like 'a cute pet'
end
...
describe 'The Doge' do
let(:pet) Doge.new
it_behaves_like 'a cute pet'
end
在玩笑中有同等的吗?是什么让我可以重用beforeEach()块中设置的变量?我正在尝试使用以下方法找到一种方法:
const cutenessTests = function() {
test('it is small', () => {
expect(petSetInBefore.length).toBeLesserThan(5)
})
test('it can smile', () => {
expect(petSetInBefore.canSmile).toBe(true)
})
}
describe('Famous animals', () => {
let petSetInBefore;
describe('Octocat', () => {
beforeEach(() => {
petSetInBefore = new Octocat();
})
cutenessTests.bind(this)()
})
})
这里重要的是,我要共享多个test
定义,而不仅仅是一个,否则我可以将petSetInBefore传递给共享函数
答案 0 :(得分:3)
您可以简单地将共享测试移动到执行it()
调用的函数中。
class Octocat {
get length() {
return 3;
}
get canSmile() {
return true;
}
}
class GrumpyCat {
get length() {
return 1;
}
get canSmile() {
return false;
}
}
const behavesLikeAPet = (pet) => {
it('is small', () => expect(pet.length).toBeLessThan(5));
it('can smile', () => expect(pet.canSmile).toEqual(true));
};
describe('Famous animals', () => {
describe('Octocat', () => {
behavesLikeAPet(new Octocat());
});
describe('GrumpyCat', () => {
behavesLikeAPet(new GrumpyCat());
});
});
您将获得每个it测试的详细输出:
Famous animals
Octocat
✓ is small (2ms)
✓ can smile (1ms)
GrumpyCat
✓ is small
✕ can smile (2ms)
答案 1 :(得分:3)
如果您仍然希望 beforeEach ,
由于某些原因...如果您在全局范围内声明变量,它会起作用
let petSetInBefore; // here it works
describe('Famous animals', () => {
//let petSetInBefore; // here it's undefined
describe('Octocat', () => {
//let petSetInBefore; // undefined too
beforeAll(() => {
petSetInBefore = new Octocat();
})
cutenessTests() // .bind(this) results the same
});
describe('Doge', () => {
beforeEach(() => {
petSetInBefore = new Doge();
})
cutenessTests.bind(this)()
});
})
https://repl.it/@gui3/jestSharedTests
似乎共享函数中的测试无法共享 beforeEach 中的变量,否则...
答案 2 :(得分:0)
Jest拥有describe.each(table)
,我还没看到它经常使用,但是对于重用具有相同/相同结果的测试确实很有帮助。
如果对两个测试主题的期望都相同,您可以这样做:
const aCutePet = pet => {
it("should be small", () => {
expect(pet.size).toBeLessThan(10);
});
it(`should be able to smile`, () => {
expect(pet).toHaveProperty('can_smile', true)
});
}
describe.each([
[new Doge],
[new Octocat]
])("The %O", aCutePet);
输出:
The Doge { size: 3, can_smile: true }
✓ should be small (1ms)
✓ should be able to smile (1ms)
The Octocat { size: 5, can_smile: true }
✓ should be small
✓ should be able to smile (1ms)