Jest 将设置/拆卸代码封装到一个函数中



我正在尝试将一些常见的设置/拆卸代码封装到如下所示的函数中:

export function testWithModalLifecycle() {
  beforeEach(() => {
    const modalRootDom = document.createElement('div')
    modalRootDom.id = ModalRootDomId
    document.appendChild(modalRootDom)
  })
  afterEach(() => {
    const modalRootDom = document.getElementById(ModalRootDomId)
    if (modalRootDom) {
      modalRootDom.remove()
    }
  })
}

并在我需要它的测试中使用它:

describe('Modal', () => {
  testWithModalLifecycle()
  it('should render a modal', () => {
    //...
  })
})

但看起来我的设置/拆卸代码从未被调用过。我做错了什么吗?这可能吗?

这可能吗?

是的,这是可能的。

您的函数只需要调用函数体内的beforeEach和同步afterEach,就像您正在做的那样,并且该函数需要在describe回调的主体中同步调用,您也在这样做。

我设置了一个测试并遇到了document.appendChild错误,但如果该行更改为document.body.appendChild则工作正常:

实用.js

export const ModalRootDomId = 'myid';
export function testWithModalLifecycle() {
  beforeEach(() => {
    const modalRootDom = document.createElement('div');
    modalRootDom.id = ModalRootDomId;
    document.body.appendChild(modalRootDom);  // <= append to the body
  });
  afterEach(() => {
    const modalRootDom = document.getElementById(ModalRootDomId);
    if (modalRootDom) {
      modalRootDom.remove();
    }
  });
}

代码测试.js

import { testWithModalLifecycle, ModalRootDomId } from './util';
describe('Modal', () => {
  testWithModalLifecycle()
  it('should render a modal', () => {
    const modalRootDom = document.getElementById(ModalRootDomId);
    expect(modalRootDom.outerHTML).toBe('<div id="myid"></div>');  // Success!
  })
})

最新更新