如何使用Jest测试传递给document.body.appendChild()的args

9

我有一个创建脚本元素并将其添加到页面主体的函数,代码看起来像这样:

const s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'https://myscript';
s.id = 'abc';

document.body.appendChild(s);

我正在使用jest进行测试,并且正在对appendChild函数进行监视,以确保传递的参数符合我的预期。我的代码如下:

jest.spyOn(document.body, 'appendChild');

doFunction();

expect(document.body.appendChild).toBeCalledWith(
  '<script id="abc" src="https://myscript" type="text/javascript" />',
);

尽管字符串匹配,但传递到appendChild的参数不是字符串,而是一个对象。
typeof document.body.appendChild.mock.child[0][0] // object

我还尝试了对一个对象进行断言({ type: '...' }),但没有成功。在jest中,还有哪些选项可以测试这段代码?

3个回答

13

正如@Alex所指出的那样,document.createElement会创建一个HTMLScriptElement对象。

您可以通过使用expect.objectContaining检查其属性来测试HTMLScriptElement是否被正确创建:

const doFunction = () => {
  const s = document.createElement('script');
  s.type = 'text/javascript';
  s.src = 'https://myscript';
  s.id = 'abc';

  document.body.appendChild(s);
}

test('doFunction', () => {
  jest.spyOn(document.body, 'appendChild');

  doFunction();

  expect(document.body.appendChild).toBeCalledWith(
    expect.objectContaining({
      type: 'text/javascript',
      src: 'https://myscript/',
      id: 'abc'
    })
  ); // Success!
});

很好 - 我喜欢这种方法,因为它测试了更多的代码,并且与 expect.any(HTMLScriptElement) 结合使用,可以测试我需要的所有内容。 - Christopher Moore
5
你好,@ChristopherMoore。我遇到了这个错误 ==> 期望值: 包含对象 {"id": "script1", "src": "app/components/myse/quoteandorderconfirmation/script/script1.js", "type": "text/javascript"},但是实际接收到的值为: <script id="script1" src="app/components/myse/quoteandorderconfirmation/script/script1.js" type="text/javascript" />。请帮忙看一下,谢谢! - Diganta

3
你可以断言appendChild被调用时传入的是一个HTML元素,这也是document.createElement返回的内容。最初的回答。
expect(document.body.appendChild).toBeCalledWith(expect.any(HTMLElement));

您可以通过检查是否使用了脚本元素来进一步澄清您的测试。最初的回答中提到了这一点。
expect(document.body.appendChild).toBeCalledWith(expect.any(HTMLScriptElement));

1
谢谢!你知道有没有办法检查调用的HTMLScriptElement吗?例如,验证src字段是否符合我的预期。 - Christopher Moore

0

另一个选项是使用jest的(可选inlinesnapshots

it('...', () => {
  doFunction()
  expect(document.documentElement).toMatchInlineSnapshot(`
      <html>
        <head>
          <!-- ...your appended nodes... -->
        </head>
        <body>
          <!-- ...your appended nodes... -->
        </body>
      </html>
    `)
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接