简体   繁体   English

摩卡-coffeescript语法

[英]Mocha - coffeescript syntax

I'm converting some Mocha tests from JS to coffeescript and having issues with the beforeEach function. 我正在将一些Mocha测试从JS转换为coffeescript,并且beforeEach函数有问题。 Below is what I currently have, but the data variable isn't being recognized in the test cases. 下面是我目前拥有的,但是在测试用例中无法识别data变量。 Any suggestions? 有什么建议么?

beforeEach ->
  data =
    name: "test name"
    to: "alice"
    from: "bob"
    object1: "foo"
    object2: "bar"

And here is the original: 这是原始的:

beforeEach(function(){
  data = {
    name: "test name",
    to: "Alice",
    from: "Bob",
    object1: "foo",
    object2: "bar"
  }
});

In your JavaScript version: 在您的JavaScript版本中:

beforeEach(function(){
    data = { ... }
});

data is a global variable because it isn't explicitly scoped to the function using var data . data是一个全局变量,因为它没有使用var data明确地作用于函数。 In your CoffeeScript version: 在您的CoffeeScript版本中:

beforeEach ->
  data = ...

data is a local variable inside the beforeEach callback function because that's how variables work in CoffeeScript : databeforeEach回调函数内部的局部变量,因为这就是CoffeeScript中变量的工作方式

Lexical Scoping and Variable Safety 词汇范围和可变安全性

The CoffeeScript compiler takes care to make sure that all of your variables are properly declared within lexical scope — you never need to write var yourself. CoffeeScript编译器会确保确保所有变量都在词法范围内正确声明-您无需自己编写var

and your CoffeeScript ends up like this JavaScript: 并且您的CoffeeScript最终像以下JavaScript所示:

beforeEach(function(){
    var data = { ... }
});

and data is hidden away where you can't see it. data隐藏在看不见的地方。

One solution is to manually create data outside the beforeEach : 一种解决方案是在beforeEach之外手动创建data

describe 'Whatever', ->
  data = null
  beforeEach ->
    data = ...

That will give you the same data inside and outside beforeEach and data should be what you're expecting inside each of your it s. 这会给你同样的data内外beforeEachdata应该是你在里面每个的期待是什么it秒。

Another option is to use an instance variable for data : 另一种选择是对data使用实例变量:

beforeEach ->
  @data = ...

and then look at @data inside your it s. 然后看看it里面的@data

I'd prefer the first version (manually scoping data with data = null ) because you never know when you're going to accidentally overwrite someone else's instance variable. 我更喜欢第一个版本(通常使用data = null确定data范围),因为您永远不知道何时意外覆盖别人的实例变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM