首页
学习
活动
专区
圈层
工具
发布

JEST _~_
EN

Stack Overflow用户
提问于 2020-12-25 19:27:58
回答 2查看 4.7K关注 0票数 1

我的职能如下:

测试代码

代码语言:javascript
复制
export default function main() {
    const createAndAppendPTag = () => {
        const p = document.createElement('p');
        document.body.appendChild(p);
    };

    window.document.addEventListener('click', () => {
        createAndAppendPTag();
    });
}

问题是:如何使用Jest断言在文档单击事件上调用了createAndAppendPTag ?

取笑

这是我试过的,但似乎无法通过测试:

代码语言:javascript
复制
import main from './main'

window.document.addEventListener = jest.fn();
const createAndAppendPTag = jest.fn();

describe('Main', () => {
    const documentClickEvent = new Event('click');

    test('appends p tag to the document', () => {
        // dispatching event before and after invoking `main` to be sure
        window.document.dispatchEvent(documentClickEvent);

        main();

        window.document.dispatchEvent(documentClickEvent);

        expect(window.document.addEventListener).toHaveBeenNthCalledWith(1, 'click', () => {});
        expect(createAndAppendPTag).toHaveBeenCalledTimes(1);
    });
});

终端

这样做的结果如下:

代码语言:javascript
复制
  Main › appends p tag to the document
    
expect(jest.fn()).toHaveBeenNthCalledWith(n, ...expected)
    
n: 1
Expected: "click", [Function anonymous]
    
Number of calls: 0
    
5   | main();
6   | window.document.dispatchEvent(documentClickEvent);
> 7 | expect(window.document.addEventListener).toHaveBeenNthCalledWith(1, 'click', () => {});
*   |                                          ^

提前谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-12-26 17:54:04

我运行了这个简化的测试来检查副作用(p元素被附加到body):

main.js

代码语言:javascript
复制
export default function main() {
  const createAndAppendPTag = () => {
    const p = document.createElement('p');
    document.body.appendChild(p);
  };

  window.document.addEventListener('click', () => {
    createAndAppendPTag();
  });
}

main.test.js

代码语言:javascript
复制
import main from `../main.js`;

it('"main" listener appends "P" to body upon click', () => {
  // add listener
  main();

  // clear body contents
  document.body.innerHTML = "";

  // dispatch click event to listener
  const addEvt = new Event('click');
  document.dispatchEvent(addEvt);

  // check for existence of "P" element
  const bodyEl = document.body.firstChild;
  expect(bodyEl).not.toEqual(null);
  expect(bodyEl.tagName).toBe('P');
  document.body.innerHTML = "";
});

它通过了:

代码语言:javascript
复制
  ✓ "main" listener appends "P" to body upon click (2 ms)
票数 3
EN

Stack Overflow用户

发布于 2020-12-26 05:53:25

您可以使用jest.spyOn(object,methodName)window.document.addEventListener()document.createElement()document.body.appendChild()方法创建模拟。

因为createAndAppendPTag函数是私有的,所以不能监视/模拟它,但是您可以通过断言它的内部方法间接地确定它是否被调用。

例如使用"jest": "^26.6.3"

main.js

代码语言:javascript
复制
export default function main() {
  const createAndAppendPTag = () => {
    const p = document.createElement('p');
    document.body.appendChild(p);
  };

  window.document.addEventListener('click', () => {
    createAndAppendPTag();
  });
}

main.test.js

代码语言:javascript
复制
import main from './main';

describe('65451115', () => {
  afterAll(() => {
    jest.restoreAllMocks();
  });
  it('should pass', () => {
    const createElementSpy = jest.spyOn(document, 'createElement').mockReturnValue('fake p');
    const appendChildSpy = jest.spyOn(document.body, 'appendChild').mockReturnValue();
    const addEventListenerSpy = jest
      .spyOn(window.document, 'addEventListener')
      .mockImplementationOnce((event, handler) => {
        handler();
      });
    main();
    expect(addEventListenerSpy).toBeCalledWith('click', expect.any(Function));
    expect(createElementSpy).toBeCalledWith('p');
    expect(appendChildSpy).toBeCalledWith('fake p');
  });
});

单元测试结果:

代码语言:javascript
复制
 PASS  examples/65451115/main.test.js (10.621 s)
  65451115
    ✓ should pass (4 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 main.js  |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        16.536 s
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65451115

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档