简体   繁体   English

对带有Tape和Sinon的ForEach进行JavaScript功能的单元测试

[英]Unit testing JavaScript function with ForEach with Tape and Sinon

I am struggling to unit test the following function. 我正在努力对以下功能进行单元测试。 In particular I cannot get it to cover the highlighted code: 特别是我无法覆盖突出显示的代码:

function authCert(trustedCAFile){
    let ca = [];
    let cert = [];
    let trustedCA = String(fs.readFileSync(trustedCAFile));
    let trustedCALines = trustedCA.split("\n");

    trustedCALines.forEach(function(entry){

    cert.push(entry);
    if(entry.match(/-END CERTIFICATE-/)){
        **ca.push(cert.join("\n"));
        cert = [];**
    }
});

return ca;
}

This is my current test: 这是我目前的测试:

let test = require('tape');
let rewire = require('rewire');
let sinon = require('sinon');
let fs = require('fs');
let proxyquire = require('proxyquire');

test('should cycle through trusted ', function(t) {
  let authCert = rewire('../authCert');
  let getAuthCerts = certUtils.getAuthCert;

  let certStub = 'test';

  let fsStub = {
      readFileSync: () => {}
  };

  let ca = [];
  ca.push('1');

  certUtils.__set__('fs', fsStub);

  let result = getAuthorisedCerts(certStub);

  t.deepEquals(result, []);
  t.end();

});

I have looked at the documentation but as a noob I am unsure how to go about getting coverage and testing the highlighted code. 我看过文档,但是作为一个菜鸟,我不确定如何进行覆盖和测试突出显示的代码。

If anyone could help me or point me in the right direction I'd be very grateful. 如果有人能帮助我或指出正确的方向,我将不胜感激。

Thanks 谢谢

You don't need proxyquire (not actually being used) or rewire to do the testing you want to do. 您不需要proxyquire (实际上并未使用)或rewire即可进行您想做的测试。

We can just use sinon to stub the fs object for the tests. 我们可以使用sinonfs对象存根进行测试。

In terms of getting the coverage you wanted, all you needed to do was to make the readFileSync stub actually return something containing at least one '-END CERTIFICATE-' . 就获得所需的覆盖率而言,您所需要做的就是使readFileSync存根实际返回包含至少一个'-END CERTIFICATE-'

const test = require('tape');
const sinon = require('sinon');
const fs = require('fs');

const certUtils = require('../authCert');
const caFilePath = 'test';

test('should return each certificate', function(t) {
  const fileContents = 'cert1\n-END CERTIFICATE-\ncert2\n-END CERTIFICATE-';
  const fsStub = sinon.stub(fs, 'readFileSync').returns(fileContents);
  const result = certUtils.getAuthCert(caFilePath);

  fsStub.restore();

  t.deepEquals(result, ['cert1\n-END CERTIFICATE-', 'cert2\n-END CERTIFICATE-']);
  t.end();
});

I've taken some liberties in terms of let/const and structuring the file, the key changes you need are making the stub return the string I've called fileContents . 我在let/const和结构化文件方面采取了一些自由,您需要进行的关键更改是使存根返回我称为fileContents的字符串。

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

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