Node,Sinon,Mocha模拟默认导出功能

时间:2020-09-25 18:50:22

标签: node.js mocha sinon es6-modules

我正在尝试模拟导入nodeVault,以便可以为read函数设置返回值。 我有以下代码:

import nodeVault from 'node-vault';

const getVaultClient = (vaultToken) => {
  return nodeVault({
    apiVersion: 'v1',
    endpoint: process.env.VAULT_URL,
    token: vaultToken.auth.client_token,
  });
}

const getCredentialsFromVault = async () => {
  const vaultToken = await getVaultToken();
  const vault = getVaultClient(vaultToken);
  const { data } = await vault.read(process.env.VAULT_SECRET_PATH);
  return { client_id: data.client_id, client_secret: data.client_secret, grant_type: 'client_credentials' };
};

然后我要进行单元测试:

describe('AttributeLoad', () => {
  let sandbox;
  let pedApiMock;
  let authApiMock;
  let vaultAuthenticateMock;
  let nodeVaultClientMock;

  beforeEach(() => {
    sandbox = createSandbox();
    process.env = {  VAULT_URL: 'testVault', VAULT_SECRET_PATH: 'testPath' };
    pedApiMock = sandbox.stub(attributeLoader.pedApi, 'post');
    authApiMock = sandbox.stub(attributeLoader.authApi, 'post');
    vaultAuthenticateMock = sandbox.stub(vaultAuthAws.prototype, 'authenticate');
    nodeVaultClientMock = sandbox.stub(nodeVault.prototype, ''); --------> Not sure what should go here 
    I have tried read and constructor
  });

  afterEach(() => {
    sandbox.restore();
  });

 it('Should call api with correct request body and correctly filter successes and rejections', async () => {
    const expectedOutput = {
      rejectedLines: [
       ....
      ],
      validLines: [
      .....
      ]
    };

    const mockAuthResponse = {
      data: {
        access_token: 'mocktoken',
      },
    };

    const mockVaultToken = {
      auth: {
        client_token: ''
      }
    };

    const expectedAuthParams = {
      client_id: '',
      client_secret: '',
      grant_type: 'client_credentials',
    };

    const mockVaultData = {
      data: {
        client_id: '',
        client_secret: '',
      }
    };

    pedApiMock.returns(Promise.resolve(mockResponse));
    authApiMock.returns(Promise.resolve(mockAuthResponse));
    vaultAuthenticateMock.returns(Promise.resolve(mockVaultToken));
    nodeVaultClientMock.returns(Promise.resolve(mockVaultData));

    const finalTestData = await attributeLoader.load(testInputData);

    assert.calledWith(authApiMock, expectedAuthParams);

    expect(finalTestData.rejectedLines).to.deep.equal(expectedOutput.rejectedLines);
    expect(finalTestData.validLines).to.deep.equal(expectedOutput.validLines);
  });

});

我尝试的所有操作都会出现此错误:

  • “在每个之前”钩子用于“应使用正确的请求正文调用api并正确过滤成功和拒绝”: TypeError:无法存根不存在的属性读取* --->或我尝试模拟的任何函数 我还尝试监视nodeVault。

任何人和所有帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

因此,在进行更多挖掘之后,我能够使用proxyquire来模拟节点保管库:

import proxyquire from 'proxyquire';

const attributeLoader = proxyquire('../src/attributeLoader', { 'node-vault': () => { return { read: () => mockVaultData } } });

然后修复它。