如何使用在同一个js文件中的describe()内的describe()外部定义的导出函数来调用该函数

时间:2017-01-20 06:49:09

标签: javascript mocha

我正在尝试写一些类似

的内容
describe('Create User', function () {
  it('1: All Data Valid', function (done) {
    servicesGenerator.postPlayoApi(apiEndPoints.createUser)
    .send(this.getValidUserCreateBody())
    .end(function (err, res) {
      validator.userDataTypeValidator(err, res);
      done();
    });
  });
});

exports.getValidUserCreateBody = function() {
  return {
    "emailId": testData.emailIdDefault,
    "fName": testData.fNameDefault,
    "lName": testData.lNameDefault,
    "gender": testData.genderDefault,   
  };
}

但它的给定错误 TypeError:this.getValidUserCreateBody不是函数 我该如何着手实施这一流程?

1 个答案:

答案 0 :(得分:3)

Hoisting得到了你。请在描述上方定义getValidUserCreateBody

此外,函数中的this与外部的this不同。尝试通过关闭使用getValidUserCreateBody

var getValidUserCreateBody = function() {
  return {
    "emailId": testData.emailIdDefault,
    "fName": testData.fNameDefault,
    "lName": testData.lNameDefault,
    "gender": testData.genderDefault,   
  };
}

exports.getValidUserCreateBody = getValidUserCreateBody; //You don't necessarily need this line if you don't use it outside this file.

describe('Create User', function () {
  it('1: All Data Valid', function (done) {
    servicesGenerator.postPlayoApi(apiEndPoints.createUser)
    .send(getValidUserCreateBody())
    .end(function (err, res) {
      validator.userDataTypeValidator(err, res);
      done();
    });
  });
});