Node、Sinon、Mocha mock 默认导出函数

Node, Sinon, Mocha mock default exported function

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

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);
  });

});

我尝试的一切都出现了这个错误:

任何帮助将不胜感激

所以在进一步挖掘之后,我能够使用 proxyquire 来模拟 node vault:

import proxyquire from 'proxyquire';

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

然后修复了它。