Jest - 模拟所需的模块功能

时间:2018-05-07 07:31:53

标签: unit-testing jest

我有以下需要测试的代码: 的 createCassandraDriver

const driver = require('cassandra-driver')
module.exports = ({
  cassandra_user,
  cassandra_password,
  cassandra_address
}) => {
  return new Promise((resolve, reject) => {
    try {
      const client = new driver.Client({
        contactPoints: cassandra_address.split(','),
        authProvider: authProvider(cassandra_user, cassandra_password),
        queryconfig: {
          consistency: driver.types.consistencies.quorum
        }
      })
      return resolve(client)
    } catch (e) {
      reject(e)
    }
  })
}

我正试图模仿对'driver.Client'的调用。 我尝试使用'spyOn'来做,就像这样:

'use strict';
const rewire = require('rewire'),
      driver = require('cassandra-driver'),
      createCassandraDriver = require('../../lib/createCassandraDriver.js');

const defaultArguments = () => {
  return {
    'cassandra_address': '127.0.0.1',
    'cassandra_user': 'cassandra_user',
    'cassandra_password': 'cassandra_password'
  };
}

jest.mock("cassandra-driver");

describe('Create cassandra driver tests', function () {
  describe('success flow', function () {
    it('Should pass without any errors ', async function () {    
        await createCassandraDriver(defaultArguments())
    });
  });
  afterEach(function () {
    jest.restoreAllMocks()
  });
});

__ mocks__ file

const driver = jest.genMockFromModule('cassandra-driver');
driver.Client = function () {return "cassandra_client"}    
module.exports = driver;

但是我收到一条错误消息,上面写着“驱动程序不是函数”,这是真的。

如何模拟对'driver.Client'的调用呢? 请指教

2 个答案:

答案 0 :(得分:2)

我建议使用Manual Mocks来模拟Jest测试中的外部依赖项。

  1. node_modules旁边创建一个名为__mocks__/cassandra-driver.js的目录。

  2. 创建文件module.exports = { types: { consistencies: { quorum: null } }, Client: jest.fn() };

  3. jest.mock("cassandra-driver");
    
    1. 在测试文件中添加以下行:
    2. cassandra-driver

      现在,每次在测试中导入import driver from "cassandra-driver"; import createCassandraDriver from "./createCassandraDriver"; jest.mock("cassandra-driver"); const clientStub = { foo: "bar" }; driver.Client.mockImplementation(() => clientStub); it("renders without crashing", async () => { const result = await createCassandraDriver({ cassandra_user: "foo", cassandra_password: "bar", cassandra_address: "baz" }); expect(result).toEqual(clientStub); }); 或在测试中导入的任何文件中,都会导入在步骤2中实现的模块。

      这允许您使用任何mock methods调用driver.Client来替换实现,存根返回值或访问模拟实例。

      这是一个完整的测试示例:

      import {Location} from '@angular/common';
      
      constructor(private location :Location){}
      
      loginAction(){
           //Do login request 
      
           //Login Success callback
           this.location.back();
           //Login Failed callback
           Do nothing
      }
      

答案 1 :(得分:1)

您只能使用jest.spyOn监视对象的方法 - 这里,drivercreateCassandraDriver模块中的私有变量,因此我们无法使用它。

您使用__set__时似乎正在使用rewire package?如果是这样,我认为您应该能够通过jest.fn

实现您想要的目标
let createCassandraDriverSpy = jest.fn(clientMock);
createCassandraDriver.__set__('driver', createCassandraDriverSpy)