Update I made some progress today, but I've encountered a new error in the same process. Updated question below.
I'm here with another query regarding how to simulate a complex call from AngularFireStore.
I'm facing an issue while running my tests with the importData function in my service. The final get call should return an array that I need to verify, but I'm struggling to set up the mock correctly, causing the test to fail.
Below is the Version 2 of my mock file, which I believe is very close to working. I've resolved all errors related to various functions, and currently, I'm getting stuck at the first IF statement that checks if the returned array's length is 0 or not. The return is unfortunately 'undefined', leading to the error.
Interestingly, when the final return in my mock is changed to return Promise.resolve()
(without an array inside the parentheses), the error changes to:
Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'docs')
. Adding the array then triggers an error related to the undefined 'length'.
I'm also considering if this issue is related to processing and fakeasync, so I've experimented with a few versions. Currently, the test uses 'fakeasync'. Another point worth noting is that changing it from 'fakeasync' to just 'async' with an await or without results in a 'pass' for the test but still throws the error in the console.
TypeError: Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'length') TypeError: Cannot read properties of undefined (reading 'length')
service.ts
importData(Id: number) {
this.afs.collection<data>('users/' + this.authService.liveUid + .ref.where('id', '==', Id).get().then(
a => {
if (a.docs.length == 0) {
if (validID(Id, 8, 9)) {
this.http.get<DataImport>('https://url' + Id).subscribe(
//do stuff
)
} else
{
this.urlError = true
this.spinnerImported = true
}
}
else {
this.spinnerImported = true
this.sameImportName = a.docs[0].get('name')
}
}
)
}
service.spec.ts
describe('ImportService', () => {
let service: ImportService;
beforeEach(() => {
TestBed.configureTestingModule(
{
providers: [
{ provide: HttpClient, useValue: httpClientMock },
{ provide: AngularFirestore, useValue: AngularFirestoreMock },
{ provide: AuthService, useValue: AuthServiceMock },
]
});
service = TestBed.inject(ImportService);
});
it('should be created', fakeasync (() => {
service.importData(32198712)
tick ()
}));
});
**AngularFirestoreMock (version 1) **
export const AngularFirestoreMock = jasmine.createSpyObj('AngularFirestoreMock', {
'doc': {
set: function () {
return Promise.resolve()
}
},
'collection':{
get: function () {
return Promise.resolve()
}
}
}
)
AngularFirestoreMock (version 2)
export const AngularFirestoreMock = jasmine.createSpyObj('AngularFirestoreMock', {
'doc': {
set: function () {
return Promise.resolve()
}
},
'collection': {
'ref': {
where: () => {
return {
get: () => {
return Promise.resolve([{ name: 'test'}])
}
}
}
}
}})