I'm writing unit test for my LWC. For some of the methods and features that I'm testing, it looks at the values of a field and then does something. For example:
let field = this.template.querySelector('.field-class');
if (field.value == 'Matching Value') {
let secondField = this.template.querySelector('.another-field-class');
secondField.value = 'Default Value';
}
So when I'm writing the test I'll have something like this:
describe('test-element', () => {
var element;
beforeEach(() => {
element = createElement('c-test-element', {
is: TestElement
});
document.body.appendChild(element);
});
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('should set the default value'), () => {
let field = element.shadowRoot.querySelector('.field-class');
field.value = 'Matching Value';
const form = element.shadowRoot.querySelector('lightning-record-edit-form');
form.dispatchEvent(new CustomEvent('load'));
let secondField = element.shadowRoot.querySelector('.another-field-class');
expect(secondField.value).toBe('Default Value');
});
});
It works fine, but the problem is that when I run the test I get a warning message like this:
console.warn
node_modules/@lwc/engine/dist/commonjs/es2017/engine.js:208
[LWC warning]: If property value decorated with @api in [object:vm undefined (213)] is used in the template, the value
Matching Value set manually may be overridden by the template,
consider binding the property only in the template.
I've found a way to avoid this by adding getters and setters to the the actual component and using those, but that doesn't seem like the best solution since I only need them for tests. Especially since to get full code coverage I have to write specific test for them.
Is there a way to set the value of a field for a test without getting the warning message?
I apologize for any typos in the code, I freehand wrote it.
Best Answer
Thanks for raising this issue. We recently cleaned up our warning and error messages because some of them were un-actionable or just creating too much noise. This particular warning will no longer be logged in a future release: https://github.com/salesforce/lwc/commit/1afe614236cd0a2c801617afbbdeaeea9b8a30ff