微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

似乎无法获得在 useEffect 内调度的 setTimeout 操作的测试覆盖率

如何解决似乎无法获得在 useEffect 内调度的 setTimeout 操作的测试覆盖率

我在使用 window.setTimeout() 获取反应动作调度的测试覆盖率时遇到问题,测试通过 done(),但它实际上并没有为伊斯坦布尔覆盖率提供任何覆盖率。我尝试了一些东西,但到目前为止没有任何效果。有没有熟悉这个测试的?我也尝试过使用 lolex 来模拟​​时间而不是使用 window.setTimeout() 但它没有说 getBrSEOData 从未被调用过。

这是我的代码

  useEffect(() => {
    if (!Config.ui.isBot) {
      window.setTimeout(() => {
        getBrSEOData(productType,productId,productName,productStatus);
      },BR_DELAY);
    }
  },[getBrSEOData,productType,productStatus]);

这是测试

  it("should make the blooomreach api call if !Config.ui.isBot",done => {
    const BR_DELAY = 6000;
    const response = {
      status: "SUCCESS",payload: {
        "related-item": bloomreachState["related-item"],"related-category": [],"more-results": []
      }
    };
    props = {
      relatedSearches: bloomreachState["related-item"],relatedCategories: bloomreachState["related-category"],relatedProducts: bloomreachState["more-results"],getBrSEOData: sinon.spy(() => new Promise(resolve => resolve({ response })))
    };
    Config.ui.isBot = false;
    component = render(<BloomreachSEO {...props} />);
    window.setTimeout(() => {
      expect(props.getBrSEOData).to.have.been.calledOnce;
    },BR_DELAY);
    done();
  });

伊斯坦布尔显示该线路没有覆盖

enter image description here

解决方法

我能够通过使用 npm 包 lolex 使其工作。如果有人在使用 React 测试库以及测试 window.setTimeout()

时遇到问题
  let clock;

  beforeEach(() => {
    clock = lolex.install({ now: 4476701471000,toFake: ["setTimeout"] });
  });

  afterEach(() => {
    clock.uninstall();
  });

  it("should make the bloomreach api call if !Config.ui.isBot",() => {
    const BR_DELAY = 5000;
    const response = {
      status: "SUCCESS",payload: {
        "related-item": bloomreachState["related-item"],"related-category": [],"more-results": []
      }
    };
    props = {
      relatedSearches: bloomreachState["related-item"],relatedCategories: bloomreachState["related-category"],relatedProducts: bloomreachState["more-results"],getBrSeoData: sinon.spy(() => new Promise(resolve => resolve({ response })))
    };
    Config.ui.isBot = false;
    component = render(<BloomreachSeo {...props} />);
    clock.tick(BR_DELAY);
    clock.setTimeout(() => {
      expect(props.getBrSeoData).to.have.been.called;
    },BR_DELAY);
  });

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。