sinon.js:为方法创建“存根”并测试忽略存根

时间:2019-11-27 10:34:41

标签: unit-testing mocking sinon stub

我在node.js中编写了以下代码:

const rp = require('request-promise');

export async function readSite() {
    try {
        let response = await rp('http://www.google.com');
        return response;
    }
    catch(err) {
        console.log(err);
    }
}

export async function main() {
    let response = await readSite();
    return response;
}

我想测试main方法。由于readSite是我不想在测试过程中运行的异步方法,因此我想对其进行模拟/存根,这意味着每当测试调用readSite方法时,它将自动获得响应(无需调用外部网站)。

const sinon = require('sinon');
const app = require("./app");

describe('when there was no ingredient', async() => {
    it('mama would be angry', async () => {
        sinon.stub(app, 'readSite').returns(Promise.resolve('blabla'));
        let res = await app.main();
        console.log("*************************************", res);
    })
})

运行测试(在终端中运行mocha ./test.js时,我看到已读取“ www.google.com”,这意味着存根没有成功。

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

这是解决方案:

index.js

const rp = require("request-promise");

async function readSite() {
  try {
    let response = await rp("http://www.google.com");
    return response;
  } catch (err) {
    console.log(err);
  }
}

async function main() {
  let response = await exports.readSite();
  return response;
}

exports.readSite = readSite;
exports.main = main;

index.spec.js

const sinon = require("sinon");
const { expect } = require("chai");
const app = require(".");

describe("main", () => {
  it("should stub readSite", async () => {
    const readSiteStub = sinon.stub(app, "readSite").resolves("blabla");
    const actual = await app.main();
    expect(actual).to.be.equal("blabla");
    readSiteStub.restore();
  });
});

带有覆盖率报告的单元测试结果:

  main
    ✓ should stub readSite


  1 passing (9ms)

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |    77.78 |      100 |       75 |    77.78 |                   |
 index.js      |    55.56 |      100 |       50 |    55.56 |           4,5,6,8 |
 index.spec.js |      100 |      100 |      100 |      100 |                   |
---------------|----------|----------|----------|----------|-------------------|

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

有关更多信息,请参见:https://github.com/facebook/jest/issues/936#issuecomment-214939935