Noa*_*oah 35 javascript testing ecmascript-6 jestjs
在rspec中你可以这样做:
let(:input) { 'foo' }
before_each do
setup_some_thing(input)
end
context 'when input is bar do
let(:input) { 'bar' }
it 'does something different' do
end
end
context 'when input is baz do
let(:input) { 'baz' }
it 'does something else different' do
end
end
Run Code Online (Sandbox Code Playgroud)
这允许您将大对象的方法调用或实例化定义为其较小部分的总和.然后,您可以在不同的上下文中覆盖那些单独的小部件.这个想法是在每次测试之前创建一个快乐路径,然后在上下文块中指定与快乐路径的偏差.
不幸的是,我似乎无法用Jest做到这一点.我尝试过以下方法:
beforeEach(() => {
let input = 'foo';
beforeEach(() => {
setupSomeThing(input);
});
describe('when input is bar', () => {
input = 'bar';
it('does something different', () => {
});
});
describe('when input is baz', () => {
input = 'baz';
it('does something different', () => {
});
});
});
Run Code Online (Sandbox Code Playgroud)
因为jest在运行任何特定的描述块之前执行每个描述块,所以输入总是'baz'.有没有人知道一个工作,或一种方法来获得rspec行为?
提前致谢!
您可以使用beforeAll获得类似的行为(尽管没有延迟评估).
beforeEach(() => {
let input = 'foo';
beforeEach(() => {
setupSomeThing(input);
});
describe('when input is bar', () => {
beforeAll(() => {
input = 'bar';
});
it('does something different', () => {
});
});
describe('when input is baz', () => {
beforeAll(() => {
input = 'baz';
});
it('does something different', () => {
});
});
});
Run Code Online (Sandbox Code Playgroud)
我发现的最好的解决方案是像这样的图书馆
https://github.com/stalniy/bdd-lazy-var
和
https://github.com/tatyshev/given2
如果您不想引入依赖项,您可以通过执行以下操作来获得类似的行为(尽管没有延迟评估):
beforeEach(() => {
let input = 'foo';
beforeEach(() => {
setupSomeThing(input);
});
describe('when input is bar', () => {
beforeAll(() => {
input = 'bar';
});
it('does something different', () => {
});
});
describe('when input is baz', () => {
beforeAll(() => {
input = 'baz';
});
it('does something different', () => {
});
});
});
Run Code Online (Sandbox Code Playgroud)