I have an input field that reads a value from an api property. Everything works fine except when I try to write a test Test to mock the data. I am assuming that I must be making some kind of mistake in my formatting.
The fields in question grab a a value from an object passed in via a public property. When I try to run a Jest test I get an error that
<template if:true={dataLoaded}>
<div class="screen">
<lightning-input label="Parent First Name"
type="text"
value={patient.LegalGuardian__r.FirstName}
onchange={handleChange}
name="firstName"
required
data-id="parentFirstName">
</lightning-input>
<lightning-input label="Parent Last Name"
value={patient.LegalGuardian__r.LastName}
onchange={handleChange}
name="lastName"
required
type="text"
data-id="parentLastName">
</lightning-input>
<lightning-input label={labels.parentVerificationText}
class="slds-required"
required
type="Checkbox">
</lightning-input>
</div>
</template>
Mock JSON file
{
"FirstName": "Adult",
"LastName": "Patient",
"LegalGuardian__r.FirstName": "test",
"LegalGuardian__r.LastName": "Guardian",
"RecordTypeId": "01209000000IlhyAAC",
"LanguagePreference__pc": "English",
"Age__pc": 50,
"Id": "0017Z00001WcRoPQAV",
"RecordType": {
"Id": "01209000000IlhyAAC"
}
}
This works just fine in practice. But whenI try to pass a JSON file to the API in a Jest test I will get errors that that the properties FirstName and LastName are undefined. I tried to pass it with JSON.parse() but that did not solve it. Is there some way to format the JSON so that it works in my tests when passed as a public property?
I have expirmented with trying to return the value with a getter to help with testing. But the test still throws the same error.
get guardianLastName() {
return this.patient.LegalGuardian__r.LastName !== undefined
? this.patient.LegalGuardian__r.LastName
: '';
}
Best Answer
As a
__r
field references a single object for a parent reference, something more like this is needed: