我想为 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/