![]() |
慷慨的柑橘 · 测试类 指定启动参数 springboot ...· 3 周前 · |
![]() |
有腹肌的扁豆 · Mybatis if test 判断 ...· 1 周前 · |
![]() |
聪明的莲藕 · RegExp.prototype.test( ...· 4 天前 · |
![]() |
发财的西红柿 · 小米汽车上市发布 鱼米之乡有哪些“小米供应商”?· 8 月前 · |
![]() |
没有腹肌的西瓜 · 2023年高性价比三星手机推荐,一起来看看三 ...· 9 月前 · |
![]() |
温柔的汉堡包 · 子弹列车bgm_子弹列车什么时候上映_子弹列 ...· 1 年前 · |
![]() |
可爱的牙膏 · 大众纯电中型轿车来了!一汽-大众ID.7 ...· 1 年前 · |
Test a Property Change
it('Renders with Hello Matt', () => { const element = createElement('c-hello-component', { is: HelloComponent, }); document.body.appendChild(element); element.person = "Matt"; return Promise.resolve().then(() => { const pTag = element.shadowRoot.querySelector('p'); expect(pTag.textContent).toEqual('Hello, Matt!'); it('Renders with showDesktopView = true', () => { const element = createElement('c-test', { is: testLWC, }); document.body.appendChild(element); element.showDesktopView = true; return Promise.resolve().then(() => { // My promise code
https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.unit_testing_using_jest_patterns
That is the same documentation I've been using. That is basically my Trial 2 approach, but document.body.appendChild(element) is before the element assignment. I tried it in that order as well, but it didn't work. The error I get back is the querySelector doesn't find the element. However, when I default the value in my code to true for showDesktopView (which I cannot leave it like that), the query selector does find the "Name" element it is looking for.
This is a closer representation of my code following what you suggested, but doens't work: it('Displays Contact Name field', () => { const element = createElement('c-test', { is: testLWC }); document.body.appendChild(element); element.showDesktopView = true; getRecordWireAdapter.emit(mockGetRecord); // Resolve a promise to wait for a rerender of the new content. return Promise.resolve().then(() => { const content = element.shadowRoot.querySelector('.myclass'); const nameField = mockGetRecord.fields.Name.value; console.log('Expected: ' + nameField) console.log('Found: ' + content.textContent); expect(content.textContent).toBe(nameField);
The error I get back is "TypeError: Cannot read property 'textContent' of null" which is recieved when the querySelector doesn't find the rendered element. Again, the test case does pass if I default the showDesktopView to true.
const content = element.shadowRoot.querySelector ('.myclass') ;
element.shadowRoot is not the common this.shadowRoot as you can find in the mozilla documentation but it is equivalent to this.template for LWC.
You can try in your code (not the jest test) if const content = this.template.querySelector('.myclass'); is resolved.
In my jest test, the element.shadowroot.querySelector does work if I default showDesktopView to true. The test case passes, it finds the name value.
I also found this in my jest test, if I use element.querySelector when default showDesktopView is true, the case fails.