typescript - Jasmine 测试用例中是否建议使用箭头功能?

根据摩卡文档,不建议使用箭头功能。

https://mochajs.org/#arrow-functions

Jasmine 也一样吗?我在Jasmine文档中找不到关于该主题的任何指针。

最佳答案

有一篇非常有趣的文章,您不应该错过:

  • Better Jasmine Tests With this

  • 这是一个引用:

    The new, better way

    For every test (and their beforeEach/afterEach hooks), jasmine sets the receiver of each function to an initially empty object. This object, which is called userContext within Jasmine's source code, can have properties assigned to it, and gets blown away at the end of each test. In an attempt to address the issues we were having, we recently switched over to assigning variables to this object, rather than declaring them within describe and then assigning them. So our original code above now looked something like this:

    describe('views.Card', function() {
      'use strict';
    
      beforeEach(function() {
        this.model = {};
        this.view = new CardView(this.model);
      });
    
      describe('.render', function() {
        beforeEach(function() {
          this.model.title = 'An Article';
          this.view.render();
        });
    
        it('creates a "cardTitle" h3 element set to the model\'s title', function() {
          expect(this.view.$el.find('.cardTitle')).toContainText(this.model.title);
        });
    


    那么,这一切意味着什么呢?我们应该在 Jasmine 中使用箭头功能吗?

    答案应该是-将箭头功能保留在您的代码中(此组合除外)
    // could be arrow
    describe("ListModel -", () =>
    {
        // local context description
        interface IMyTestContext
        {
            items?: Heroe[];
            ...
        }
        // could be arrow
        describe("Test items ", () =>
        {
            // NOT AN ARROW - profit from Jasmine context passed as 'this'
            beforeEach(function()
            {
                var ctx: IMyTestContext = this.TestContext = {}; 
                // TODO do some defaults with context
                ...
            });
    
            // NOT AN ARROW - profit from Jasmine context passed as 'this'
            it("should ...", function()
            {
                var ctx: IMyTestContext = this.TestContext;
                // TODO ... test expecations
            ...
    

    因此, beforeEach() it() 请勿使用箭头-从 this 表示的 Jasmine 上下文中获利

    我们还可以引入全局调用 beforeEach
    import * as something from "...";
    
    beforeEach(function()
    {
        this.TestContext = {};
    });
    

    现在上下文始终在我们身边,因此我们不必重新创建它:
    describe("Track Changed items ", () =>
    {
        // NOT AN ARROW - profit from Jasmine context passed as 'this'
        beforeEach(function()
        {                                              // created by global beforeEach above
            var ctx: IMyTestContext = this.TestContext;//  = {}; 
    

    Yes, that is really so amazing, that if a test runner will find some global beforeEach ... it will also run it before each test... awesome, is not it?