javascript 茉莉花中的全局`beforeEach`?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10560716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:16:03  来源:igfitidea点击:

Global `beforeEach` in jasmine?

javascriptunit-testingjasmine

提问by Freewind

I'm using Jasmine to write tests.

我正在使用 Jasmine 编写测试。

I have several test files, each file has a beforeEach, but they are exactly the same.

我有几个测试文件,每个文件都有一个beforeEach,但它们完全一样。

How do I provide a globalbeforeEachfor them?

我如何为他们提供全局beforeEach

采纳答案by x1a4

You can put it in your spec_helper.jsfile and it should work fine.

你可以把它放在你的spec_helper.js文件中,它应该可以正常工作。

回答by Blaise

x1a4's answer confused me. This may be more clear:

x1a4 的回答让我很困惑。这可能更清楚:

When you declare a beforeEachfunction outsideall describeblocks, it will trigger before each test (so before each it). It does not matter if you declare the beforeEachbefore or after your describeblocks.

当你所有块之外声明一个beforeEach函数时,它会在每次测试之前触发(所以在 each 之前)。声明块之前还是之后都没有关系。describeitbeforeEachdescribe

It's not mentioned in the documentation.

文档中没有提到它。

// Example: 

beforeEach(function() {
    localStorage.clear();
});

describe('My tests', function() {
    describe('Test localstorage', function() {

        it('Adds an item to localStorage', function() {
            localStorage.setItem('foo', 'bar');
            expect(localStorage.getItem('foo')).toBe('bar');
        });

        it('Is now empty because our beforeEach cleared localStorage', function() {
            expect(localStorage.getItem('foo')).toBe(null);
        });

    });
});