【问题标题】:Unit Test for a function with got module using sinon使用 sinon 对带有 got 模块的函数进行单元测试
【发布时间】:2020-02-24 15:04:53
【问题描述】:

我有两个功能,

const callAndParseHttp = async (url) => {
      const response = await got(url);
       return await parseXml(response.body);
};

const parseXml = async xmlData => {
      try {
            const json = parser.toJson(xmlData.body);
            return JSON.parse(json);
      } catch (err) {
            return err;
      }
 };

我在 sinon 中写了一个单元测试,看起来像,

describe('/ handler', () => {
    let spy;
    before(() => {
        spy = sinon.spy(unitParser, 'callAndParseHttp');
    });
afterEach(() => {
    spy.restore();
});
it('unit parser testing', async () => {
    await unitParser.callAndParseHttp(
        'http://www.mocky.io/v2/5e34242423'
    );
    expect(spy.callCount).to.equal(1);
});
})

我需要为此测试创建存根吗?我是单元测试的新手。测试正确通过。

【问题讨论】:

    标签: javascript node.js mocha.js chai sinon


    【解决方案1】:

    这样你就没有完全测试它。更好的方法是使用nock 模拟http 调用并端到端测试函数。您可以在此处查看示例

    https://www.npmjs.com/package/nock

    您正在测试的方式,它并没有真正测试任何东西,因为它完全用您正在使用的spy 替换了函数。

    【讨论】:

    • spy 还是 stub 更适合这里?提前致谢。
    • @LakshmipriyaMukundan 我猜你不需要使用间谍或存根。只需使用 sinon 并模拟响应。如果你愿意,你可以使用 nock 和 spy。
    猜你喜欢
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 2020-08-13
    • 2016-12-21
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多