使用Sinon模拟Knex查询

时间:2018-05-23 07:56:18

标签: node.js unit-testing sinon knex.js

我希望创建单元测试来测试我的代码。我想嘲笑knex代码的响应,如下面的

async function getDataById({ id }) {
return knex
    .from('data')
    .select(
        'a AS A',
        'b as B',
    )
    .where('id', id);}

我最近更改为使用Knex,因此我的测试是

describe('Data Get', () => {
let dBStub;
before(() => {
    dBStub = sinon.stub(conn, 'executeQuery');
    dBStub.withArgs(sinon.match.string, validId).returns(data);
});

after(() => {
    conn.executeQuery.restore();
});

it('Should provide prices for valid ID', () =>
    pricesDb
        .get({ id: validId })
        .should.eventually.deep.equal({ data: expected }));

我不再拥有执行查询方法,只有一个knex文件。

如何转换测试以提供模拟getDataById函数的响应?

当我将存根转换为getDataByID方法时,我收到以下错误:TypeError:不能存根不存在的属性

1 个答案:

答案 0 :(得分:0)

以下是用于测试getDataById功能的单元测试:

index.ts

import { knex } from "./db";

export async function getDataById({ id }) {
  return knex
    .from("data")
    .select("a AS A", "b as B")
    .where("id", id);
}

db.ts

import Knex from "knex";

export const knex = Knex({
  client: "pg",
  connection: {
    host: "127.0.0.1",
    user: "your_database_user",
    password: "your_database_password",
    database: "myapp_test"
  }
});

index.spec.ts

import { getDataById } from "./";
import sinon from "sinon";
import { expect } from "chai";
import { knex } from "./db";

describe("getDataById", () => {
  it("should mock response", async () => {
    const mResponse = { id: 1 };
    const selectStub = sinon.stub().returnsThis();
    const whereStub = sinon.stub().resolves(mResponse);
    sinon.stub(knex, "from").callsFake((): any => {
      return {
        select: selectStub,
        where: whereStub
      };
    });
    const actual = await getDataById({ id: 1 });
    expect(actual).to.be.deep.eq(mResponse);
  });
});

覆盖率100%的单元测试结果:

  getDataById
    ✓ should mock response


  1 passing (45ms)

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |      100 |      100 |      100 |      100 |                   |
 db.ts         |      100 |      100 |      100 |      100 |                   |
 index.spec.ts |      100 |      100 |      100 |      100 |                   |
 index.ts      |      100 |      100 |      100 |      100 |                   |
---------------|----------|----------|----------|----------|-------------------|

源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/50482860