Я пытаюсь добавить некоторые тесты на основе созданных мною облачных функций Firebase.
В данный момент я пытаюсь выполнить модульный тест для получения списка данных из хранилища, но я получаю следующую ошибку при запускеtest.
Ошибка типа: doc.data не является функцией
Прежде всего рабочий API для извлечения списка данных шаблонов
import { Request, Response } from 'express';
import { db } from '../db';
/**
* The specific TemplatesController used by the templates route handler.
*/
export default class TemplatesController {
/**
* A static method used to read all Template documents.
* @param req The request received by the API Rest
* @param res The response sent by the API Rest
* @param next The next function executed in the app's middleware
*/
public async readAll(req: Request, res: Response) {
try {
const dataArray = new Array();
//Fetching all the templates
const templateQuerySnapshot = await db.collection('templates').get();
//Mapping through the templates result into a new array
templateQuerySnapshot.forEach(doc => {
dataArray.push({
id: doc.id,
data: doc.data()
});
});
//Send the response.
res.send({ status: 200, response: dataArray });
return dataArray;
} catch (error) {
res.send({ status: 500, response: error });
return error;
}
}
Основная логика состоит в том, чтобы получить шаблоны из магазина и затем отобразить результаты в новом массиве. Обратите внимание на doc.data ()
Ответ:
{
id: '1',
data: {
url: 'https://example.com',
width: 600,
height: 600
}
}
А теперь юнит-тест для конкретного вызова API.
import 'jest';
import TemplatesController from '../src/controllers/templates.controller';
const test = require('firebase-functions-test')();
const mockQueryResponse = jest.fn();
mockQueryResponse.mockReturnValue([
{
id: '1',
url: 'https://example.com',
width: 600,
height: 600
}
]);
jest.mock('firebase-admin', () => ({
initializeApp: jest.fn(),
firestore: () => ({
collection: jest.fn(path => ({
get: mockQueryResponse
}))
})
}));
const templatesController = new TemplatesController();
describe('Templates', () => {
it('should fetch all the templates', async () => {
const req = { user: 'testmail@test.com' };
const res = {
send: (status: any, response: any) => {
console.log('status is ', status);
console.log('response is ', response);
}
};
const wrapped = await test.wrap(templatesController.readAll(req as any, res as any));
console.log('wrapped', wrapped);
expect(wrapped.length).toEqual(1);
});
});
Я ожидал, что выводом будет поддельный массив, но вместо этого я получаю состояние ошибки 500 и сообщение о том, что doc.data не является функцией. Я подозреваю, что долженкак-то издеваться над doc.data ()