我有一个创建脚本元素并将其添加到正文的函数。看起来像这样:
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: '...' }
)进行断言,但是运气不好。还有什么其他选择可以测试这部分代码?
答案 0 :(得分:2)
您可以断言appendChild
是用HTML元素调用的,而HTML元素就是document.createElement
返回的内容。
expect(document.body.appendChild).toBeCalledWith(expect.any(HTMLElement));
您可以通过检查是否已通过脚本元素调用来进一步阐明测试。
expect(document.body.appendChild).toBeCalledWith(expect.any(HTMLScriptElement));
答案 1 :(得分:2)
@Alex指出,extension Formatter {
static let iso8601 = ISO8601DateFormatter()
}
let dateStr = "1996-11-24T09:02:32Z"
Formatter.iso8601.date(from: dateStr) // "Nov 24, 1996 at 2:32 PM"
创建一个document.createElement
对象。
您可以通过使用HTMLScriptElement
检查HTMLScriptElement
的属性来测试其是否正确创建:
expect.objectContaining
答案 2 :(得分:0)
另一种选择是使用笑话(可选inline
)snapshots
:
it('...', () => {
doFunction()
expect(document.documentElement).toMatchInlineSnapshot(`
<html>
<head>
<!-- ...your appended nodes... -->
</head>
<body>
<!-- ...your appended nodes... -->
</body>
</html>
`)
})