摩卡范围function未定义

我目前正在浏览一些使用Javascript的TTD教程,并且有一个似乎是Javascript而不是TTD问题的东西。

即,我有以下testing:

'use strict'; var chai = require('chai'); var expect = chai.expect; var sinon = require('sinon'); var orderSystemWith = require('../lib/orders'); //describe is used to display features //context is used to display scenarios //it is used to describe tests within a feature/scenario describe('Customer displays order', function () { beforeEach(function(){ this.orderDAO = { byId: sinon.stub() }; this.orderSystem = orderSystemWith(this.orderDAO); }) context('Given that the order is empty', function(){ beforeEach(function(){ this.orderId = 'some empty order id'; this.orderDAO.byId.withArgs(this.orderId).returns([]); this.result = this.orderSystem.display(this.orderId); }) it('will show no order items', function(){ expect(this.result).to.have.property('items').that.is.empty; }); it('will show 0 as the total prince', function(){ expect(this.result).to.have.property('totalPrice').that.is.equal(0); }); it('will only be possible to add a beverage', function(){ expect(this.result).to.have.property('actions').that.is.deep.equal([{ action:'append-beverage', target: this.orderId, parameters: { beverageRef: null, quantity: 0 } }]) }); }); }); 

orders.js看起来像这样:

 module.exports = function(orderDAO){ this.display = [] } 

当我运行testing时,出现以下错误:

 1) Customer displays order Given that the order is empty "before each" hook for "will show no order items": ReferenceError: orderSystem is not defined at Context.<anonymous> (test/customer_displays_order.js:22:27) 

错误所指的是这一行:

 this.result = this.orderSystem.display(this.orderId); 

有人能告诉我我做错了什么吗? 在我看来,这是一个范围问题…

摩卡中描述的块是对象。 当你分配一些东西到this想法是分配一个属性的对象。 由于内部描述块(上下文块是相同的东西)正在创build一个新的上下文,所以它还没有导致它抛出的orderSystem属性。

使用箭头函数或绑定在内部块可能会解决您的问题。 我倾向于find像这样嵌套块时,使用variables作用域到外部块是一个更清洁。

跟进@aaroncrows的答案:

通过使用词法箭头函数(ES6构造),后续描述块的范围可以访问外部描述块(“this”)的上下文。 这是你的代码词法箭头function。

  describe('Customer displays order', function () { beforeEach( () => { this.orderDAO = { byId: sinon.stub() }; this.orderSystem = orderSystemWith(this.orderDAO); }) context('Given that the order is empty', () => { beforeEach( () => { this.orderId = 'some empty order id'; this.orderDAO.byId.withArgs(this.orderId).returns([]); this.result = this.orderSystem.display(this.orderId); }) it('will show no order items', () => { expect(this.result).to.have.property('items').that.is.empty; }); it('will show 0 as the total prince', () => { expect(this.result).to.have.property('totalPrice').that.is.equal(0); }); it('will only be possible to add a beverage', () => { expect(this.result).to.have.property('actions').that.is.deep.equal([{ action:'append-beverage', target: this.orderId, parameters: { beverageRef: null, quantity: 0 } }]) }); }); }); 

如果你不熟悉箭头function,我会强烈build议你在周围进行一些更深入的解释。 请注意,通过使用箭头函数,您的上下文(或“this”)指向它所在的最高范围。 在这种情况下,这是您的描述块的匿名函数声明(即代码的第一行)。 但是,在不嵌套在函数块内的词法箭头函数中访问“this”时,可能正在访问全局上下文(例如,如果代码正在浏览器中执行,则为Window对象)。

希望有所帮助!