[英]How do I write a unit test in jest for a class function in the database layer of my javascript web application?
I am using jest to write unit tests for my Express app.我正在使用 jest 为我的 Express 应用程序编写单元测试。 I am new with testing as well as using jest, so I am having a difficult time writing a unit test for my class functions that represent my database layer of my application.我是测试和使用 jest 的新手,所以我很难为代表我的应用程序的数据库层的 class 函数编写单元测试。 When I run the test, the program tries to make a call to the db, but is unable to do so, falling to the catch block.当我运行测试时,程序尝试调用数据库,但无法这样做,落到了 catch 块。 Where did I go wrong?我在哪里 go 错了? Thank you.谢谢你。
// summary.ts // 摘要.ts
import db from '../db/index';
import { generateError } from '../lib/generateError';
const SummaryModel = class {
static async findAll() {
const text = `SELECT * FROM public.summary`;
let result : any = {};
try {
result = await db.query(text);
} catch(e) {
if (e) {
throw generateError(500, 'could not query db');
}
}
const summaries = {
record: result.rows,
count: result.rowCount
}
return summaries;
}
}
export default SummaryModel;
// summary.test.js // 摘要.test.js
const SummaryModel = require('../../../src/models/summary');
jest.mock('../../../src/models/summary');
test('should return an object with an array and number', async done => {
const summaries = await SummaryModel.default.findAll();
expect(typeof summaries.record).toBe('array');
expect(typeof summaries.count).toBe('number');
done();
});
// summary.test.js UPDATED // summary.test.js 已更新
const SummaryModel = require('../../../src/models/summary');
jest.mock('../../../src/models/summary');
test('should return an object with an array and number', async done => {
const SummaryModel = {
default: {
findAll: jest.fn()
},
}
const resp = {
record: [{},{}],
count: 2,
}
SummaryModel.default.findAll.mockResolvedValue(resp);
const summaries = await SummaryModel.default.findAll();
expect(summaries.record.length).toBe(2);
expect(summaries.count).toBe(2);
expect(typeof summaries.record).toBe('object');
expect(typeof summaries.count).toBe('number');
done();
});
The idea is to mock the values which would be normally returned by your method.这个想法是模拟通常由您的方法返回的值。 To do so, you can use the function mockResolvedValue
to bypass the call to the DB and return the test data you want everytime findAll
is invoked.为此,您可以使用 function mockResolvedValue
绕过对 DB 的调用,并在每次调用findAll
时返回所需的测试数据。 For instance you could have something like:例如,你可以有类似的东西:
SummaryModel.default.findAll.mockResolvedValue({
record: [{}, {}], // return some test data here
count: 2,
}
Check Jest documentation on how to mock modules.查看 Jest 文档以了解如何模拟模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.