繁体   English   中英

Sinon、递归和 setTimeout

[英]Sinon , recursion and setTimeout

我通过stackoverflow查看了这个问题,但似乎大多数问题涵盖了三个问题中的两个,并且大多数人不需要使用所有三个问题。

这是代码片段。 我试图让testA在某个超时后递归地调用自己。

const testA = async () => {
  setTimeout(() => {
    testA();
  }, 1000);
  return;
};

这是我的测试代码:

//test.js
const someThing = require("../tester.js");
const chai = require("chai");
const sinonChai = require("sinon-chai");
const sinon = require("sinon");
chai.use(sinonChai);

describe("Test A", () => {
  it("Should call twice", () => {
    const clock = sinon.useFakeTimers();
    const testASpy = sinon.spy(someThing, "testA");

    testASpy();
    chai.expect(testASpy).to.have.been.calledOnce; //is fine
    clock.tick(1000);
    chai.expect(testASpy).to.have.been.calledTwice; //fails
  });
});

我一直看到每个人都在说“Sinon 不能存根独立函数”,但我不知道为什么。 如果有人能指出我阅读更多关于它的方向,我真的很想看到这一点。 同时,如果有人知道如何解决这个问题,我也很想知道更多。 再次感谢!

你的代码没有意义。 会导致无限循环。 这是单元测试解决方案:

index.ts

export const testA = async () => {
  setTimeout(() => {
    console.count("testA");
    testA();
  }, 1000);
};

index.spec.ts

import * as mod from "./";
import sinon from "sinon";
import { expect } from "chai";

describe("58843454", () => {
  it("should pass", async () => {
    const clock = sinon.useFakeTimers();
    const testASpy = sinon.spy(mod, "testA");
    await testASpy();
    expect(testASpy.calledOnce).to.be.true;
    clock.tick(1000);
    expect(testASpy.calledTwice).to.be.true;
  });
});

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

 58843454
testA: 1
    ✓ should pass


  1 passing (16ms)

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |      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/58843454

暂无
暂无

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

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