使用Mocha在类中的函数中测试变量

时间:2019-06-04 13:53:01

标签: javascript unit-testing mocha chai

我需要在TASK类的pullPackage()函数中测试url变量的值。

class TASK {
  constructor(taskData, done) {
    //some code
  }

  // Generic Setup

  pullPackage() {
    return new Promise((resolve, reject) => {
      fs.emptydir(this.taskDir, (err) => {
        if (err) return reject(err);
        const git = require('simple-git')(this.taskDir);

        let url = '';
        console.log(process.env.NODE_ENV);
        if (process.env.NODE_ENV === 'test') {
          // url = 'ssh://testuser@127.0.0.1:4000/testuser/test-repo-1.git'; // make this match the below format
          url = '/git/testuser/test-repo-1';
        } else {
          const gitAddress = new URL(config.config.GIT_ADDRESS);
          url = `${gitAddress.protocol}//runner:${this.taskData.gitJWT}@${gitAddress.hostname}:${gitAddress.port}${this.taskData.repo}.git`;
        }
        // console.log(url);
        // const url = `${gitAddress.protocol}//runner:${this.taskData.gitJWT}@${gitAddress.hostname}:${gitAddress.port}${this.taskData.repo}.git`;
        this.logger.log('Cloning from', url);
        return git.clone(url, 'repo', (cloneErr) => {
          if (cloneErr) return reject(cloneErr);
          // console.log(url);
          // console.log(resolve);
          return resolve(true);
        });
      });
    });
  }
}

我正在使用Mocha和Chai进行此操作。我对此功能进行了两次测试,以检查变量和Promise。第二个测试按预期运行,但是第一个总是返回失败,返回AssertionError: expected undefined not to be undefined。我认为问题是我在测试期间如何访问变量。目前,我正在这样做:expect(result.url).to.not.be.undefined;我正在正确处理吗?

describe('Test MenloLab Runner - Task Class', () => {
  describe('Pull Package', () => {
    it('Check URL constant.', () => task.pullPackage().then((result) => {
      expect(result.url).to.not.be.undefined; // adjust the access method
    }));

    it('It should pull package from GIT.', () => task.pullPackage().then((result) => {
      expect(result).to.be.true;
    }));
  });
});

1 个答案:

答案 0 :(得分:0)

可以通过监视git.clone方法来完成检查URL的解决方法。为此,我们需要使用Sinon

我尚未测试您的代码,但为您提供了以下解决方案的线索:

const sinon = require('sinon');
const git = require('simple-git');

describe('Test MenloLab Runner - Task Class', () => {
  describe('Pull Package', () => {
    it('Check URL constant.', () => {
      return task.pullPackage().then((result) => {
        sinon.spy(git, 'clone'); // spying on git.clone method

        expect(result.url).to.not.be.undefined; // adjust the access method

        const expectedUrl = 'my-expected-not-undefined-url';
        sinon.assertCalledWith(git.clone, expectedUrl); // we check whether git.clone is called with not undefined URL
       });
    });

    it('It should pull package from GIT.', () => task.pullPackage().then((result) => {
      expect(result).to.be.true;
    }));
  });
});

希望有帮助