首页 > 解决方案 > isElementInViewport 的 JavaScript 测试用例

问题描述

我是测试用例的新手,谁能帮我编写isElementInViewportJavaScript 函数的测试用例

function isElementInViewport(ele) {
  const rect = ele.getBoundingClientRect()
  const InViewPort = (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= 0 &&
    rect.right <= 0
  )
  return InViewPort
}

标签: javascriptjestjstestcase

解决方案


这是解决方案:

index.ts

export function isElementInViewport(ele) {
  const rect = ele.getBoundingClientRect();
  const InViewPort =
    rect.top >= 0 && rect.left >= 0 && rect.bottom <= 0 && rect.right <= 0;
  return InViewPort;
}

index.spec.ts

import { isElementInViewport } from "./";

describe("isElementInViewport", () => {
  it("t-1", () => {
    const mEl = {
      getBoundingClientRect: jest
        .fn()
        .mockReturnValueOnce({ top: 0, left: 0, bottom: 0, right: 0 })
    };
    const actual = isElementInViewport(mEl);
    expect(actual).toBeTruthy();
    expect(mEl.getBoundingClientRect).toBeCalledTimes(1);
  });
});

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

 PASS  src/stackoverflow/59057693/index.spec.ts
  isElementInViewport
    ✓ t-1 (5ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.018s, estimated 12s

源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59057693


推荐阅读