[英]How to test dynamic changes to the DOM via JavaScript with Jest or some other testing library?
I am dynamically adding a <script>
tag to the document <head>
on page load based on the environment.我根据环境在页面加载时向文档
<head>
动态添加<script>
标记。
The Function:功能:
export const loadScript = () => {
// load script tag into head
const HEAD = document.getElementsByTagName('head')
const SCRIPT_TAG = document.createElement('script')
SCRIPT_TAG.setAttribute('src', process.env.SCRIPT_SRC)
SCRIPT_TAG.setAttribute('async', true)
HEAD[0].append(SCRIPT_TAG)
}
I want to write a test that checks if once the loadScript()
function is run that the <script>
tag made it into the head.我想编写一个测试来检查
loadScript()
函数是否在运行后<script>
标记进入头部。 Our environment is set up with Jest, and I haven't found a satisfactory example that demonstrates how to do it, or works.我们的环境是用 Jest 设置的,我还没有找到一个令人满意的示例来演示如何做到这一点或如何工作。
I am new to testing, and would appreciate any solutions, or hints offered.我是测试新手,希望能提供任何解决方案或提示。
I suppose the easiest way to test it would be something like this: 我想最简单的测试方法是这样的:
test('loadScript', () => {
process.env.SCRIPT_SRC = 'the-src';
loadScript();
expect(document.head.innerHTML).toBe('<script src="the-src" async="true"></script>');
});
This works because the default test environment for Jest
is jsdom
which simulates the document
. 这是有效的,因为
Jest
的默认测试环境是模拟document
jsdom
。
test('loadScript', () => {
loadScript();
const script = document.getElementsByTagName('script')[0];
// trigger the callback
script.onreadystatechange(); // or script.onLoad();
expect("something which you have on load").toBe('expected result on load');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.