我将使用supertest 为您的案例编写测试。我们可以使用jest.mock() 模拟ItemService 模块,并使用.mockRejectedValueOnce() 方法模拟ItemService.findAll() 方法的拒绝值。
例如
app.ts:
import express from 'express';
import type { Request, Response } from 'express';
import type { Item } from './ItemService';
import * as ItemService from './ItemService';
const app = express();
app.get('/', async (req: Request, res: Response) => {
try {
const items: Item[] = await ItemService.findAll();
res.status(200).send(items);
} catch (e) {
res.status(500).send(e.message);
}
});
export { app };
ItemService.ts:
export interface Item {}
const items = { a: '1', b: '2' };
export const findAll = async (): Promise<Item[]> => Object.values(items);
app.test.ts:
import { app } from './app';
import request from 'supertest';
import * as ItemService from './ItemService';
import { mocked } from 'ts-jest/utils';
jest.mock('./ItemService');
const mItemService = mocked(ItemService);
describe('66582815', () => {
it('should get status code 500 and an error message', (done) => {
const mError = new Error('network');
mItemService.findAll.mockRejectedValueOnce(mError);
request(app)
.get('/')
.expect(500)
.end((err, res) => {
if (err) return done(err);
expect(res.text).toBe('network');
done();
});
});
});
测试结果:
PASS examples/66582815/app.test.ts
66582815
✓ should get status code 500 and an error message (16 ms)
----------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------------|---------|----------|---------|---------|-------------------
All files | 80 | 100 | 50 | 90.91 |
ItemService.ts | 60 | 100 | 0 | 100 |
app.ts | 90 | 100 | 100 | 88.89 | 12
----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.073 s