javascript - 在 Jest 中模拟动态 html 元素

标签 javascript reactjs mocking jestjs

我想为 utils 方法编写一个测试。在该方法中,我通过 id 获取一个 html 元素,然后更改该元素的颜色。问题是该元素仅在单击按钮后才可用。我如何模拟该元素?

UtilListItem.js

import variables from '../stylesheets/Variables.scss';

export function activeListItem(props){
 let listItem = document.getElementById(props.id);
 listItem.style.backgroundColor = variables.whiteGray;
 return listItem;
}

UtilListeItem.test.js

it('check if the correct color is set for the acitve list item', () => {
  let props = {id:'123'}
  const listItem = activeListItem(props);
  expect(listItem.style.backgroundColor).toBe('#ededed');
});

错误

TypeError: Cannot read property 'style' of null

最佳答案

我向你推荐jest.spyOn 。这是监视函数和/或附加一些模拟行为的非常方便的方法。

你可以像这样使用它:

import { activeListItem } from './utils';

let spy;
beforeAll(() => {
  spy = jest.spyOn(document, 'getElementById');
});

describe('activeListItem', () => {
  describe('with found element', () => {
    let mockElement;
    beforeAll(() => {
      // Here you create the element that the document.createElement will return
      // It might be even without an id
      mockElement = document.createElement(....);
      spy.mockReturnValue(mockElement);
    });

    // And then you could expect it to have the background
    it('should have the background applied', () => {
      expect(mockElement.style.backgroundColor).toBe('#ededed');
    });
  });

  describe('without found element', () => {
    // And here you can create a scenario
    // When document.createElement returns null
    beforeAll(() => {
      spy.mockReturnValue(null);
    });

    // And expect you function not to throw an error
    it('should not throw an error', () => {
      expect(() => activeListItem({id:'123'})).not.toThrow();
    });
  });
});

模拟 .scss 文件也是一个好主意,因为它是实用程序文件的依赖项,这样当它更改时就不会影响您的单元测试。

关于javascript - 在 Jest 中模拟动态 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56785464/

相关文章:

javascript - 获取innerHTML AS HAS BEEN CHANGED

JavaScript 编码语法?

reactjs - 使用 useState 或 useRef (React) 将值清除到输入中

javascript - 如何使用 React 预加载背景图像?

android - 如何在 Android 中模拟 DateFormat.is24HourFormat() 进行单元测试?

javascript - 您使用过哪些 JavaScript 单元测试和模拟框架?

javascript - Javascript 函数故意返回未定义的值是典型的吗?

node.js - ReactJS 使用 POST 和 GET 发出跨域请求失败,代码为 405

ios - 在单元测试中使用不可用的初始值设定项模拟 Cocoa 对象

javascript - 当用户在 emberjs 2 中选择一个项目时隐藏列表