简体   繁体   English

如何开玩笑地模拟膝关节数

[英]How to mock knex count with jest

I am trying to mock a knex connection to induce failure so I can cover the exception cases of my flow.我正在尝试模拟 knex 连接以引起故障,以便我可以涵盖流程的异常情况。 I have found on this answer a way to mock inside de mocks folder, but I am not having any luck.我在这个答案中找到了一种在 de mocks文件夹中进行模拟的方法,但我没有任何运气。 My query is to count how many entries we have in a table:我的查询是计算表中有多少条目:

const db = require("../db/Client");
const logger = require("../utils/Logger");

const createUser = async () => {
    return db("users")
        .count()
        .then(data => {
            return data[0].count;
        })
        .catch(error => {
            logger.error(JSON.stringify(error));
            return null;
        });
};

module.exports = createUser;

And I am trying to mock like this:我试图像这样嘲笑:

module.exports = () => ({
    select: jest.fn().mockReturnThis(),
    then: jest.fn().mockImplementation(() => {
        throw new Error("I am an exception");
    })
});

However, I am getting db("users") is not a function.但是,我得到db("users")不是一个函数。 Help?帮助?

You can use jest.mock(moduleName, factory, options) to mock the db manually.您可以使用jest.mock(moduleName, factory, options)手动模拟db

Eg index.js :例如index.js

const db = require('./db/client');

const createUser = async () => {
  return db('users')
    .count()
    .then((data) => {
      return data[0].count;
    })
    .catch((error) => {
      console.log(error);
      return null;
    });
};

module.exports = createUser;

./db/client.js : ./db/client.js

// knex

index.test.js : index.test.js

const createUser = require('./');
const db = require('./db/client');

jest.mock('./db/client', () => {
  const mKnex = { count: jest.fn() };
  return jest.fn(() => mKnex);
});

describe('60357935', () => {
  it('should count user', async () => {
    const mData = [{ count: 10 }];
    db().count.mockResolvedValueOnce(mData);
    const actual = await createUser();
    expect(actual).toBe(10);
  });

  it('should handle error', async () => {
    const mError = new Error('network');
    db().count.mockRejectedValueOnce(mError);
    const actual = await createUser();
    expect(actual).toBeNull();
  });
});

Unit test results with 100% coverage: 100% 覆盖率的单元测试结果:

 PASS  stackoverflow/60357935/index.test.js (5.972s)
  60357935
    ✓ should count user (11ms)
    ✓ should handle error (65ms)

  console.log stackoverflow/60357935/index.js:2895
    Error: network
        at /Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/60357935/index.test.js:18:20
        at step (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/60357935/index.test.js:33:23)
        at Object.next (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/60357935/index.test.js:14:53)
        at /Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/60357935/index.test.js:8:71
        at new Promise (<anonymous>)
        at Object.<anonymous>.__awaiter (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/60357935/index.test.js:4:12)
        at Object.<anonymous> (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/60357935/index.test.js:17:29)
        at Object.asyncJestTest (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:100:37)
        at resolve (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:43:12)
        at new Promise (<anonymous>)
        at mapper (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:26:19)
        at promise.then (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:73:41)
        at process._tickCallback (internal/process/next_tick.js:68:7)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.js |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        7.484s

Another option is to use knex-mock-client , which replaces real DB connection with a fake one.另一种选择是使用knex-mock-client ,它用假的连接替换真实的数据库连接。

const knex = require('knex');
const { getTracker, MockClient } = require('knex-mock-client';
const createUser = require('./');
const db = require('./db/client');

jest.mock('./db/client', () => {
  return {
    db: knex({ client: MockClient })
  };
});

describe('60357935', () => {
  let tracker;

  beforeAll(() => {
    tracker = getTracker();
  });

  afterEach(() => {
    tracker.reset();
  });

  it('should count user', async () => {
    const mData = { count: 10 };
    tracker.on.select('users').responseOnce([mData]);

    const actual = await createUser();
    expect(actual).toBe(mData.count);
  });

  it('should handle error', async () => {
    const mError = new Error('network');
    tracker.on.select('users').simulateErrorOnce('network');

    const actual = await createUser();
    expect(actual).toBeNull();
  });
});

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

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