gpt4 book ai didi

typescript - Jasmine 测试用例中是否推荐使用箭头函数?

转载 作者:搜寻专家 更新时间:2023-10-30 20:35:28 25 4
gpt4 key购买 nike

根据 mocha 文档,不鼓励使用箭头函数。

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

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

最佳答案

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

这是一个引用:

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?

关于typescript - Jasmine 测试用例中是否推荐使用箭头函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38915090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com