用Sinon模拟Knex查询

问题描述 投票:1回答:1

我正在寻找创建单元测试来测试我的代码。我想模拟来自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:无法存根不存在的自有属性

node.js unit-testing sinon knex.js
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.