【发布时间】:2021-03-09 06:52:38
【问题描述】:
你好,我开始用 jest 研究单元测试,我有一个类有一个返回函数我想测试该函数的返回,但我不知道正确的方法是什么
类:
interface HelloWord {
hello: string
}
export class HelloWordController extends Controller{
async handle (request: HelloWord): Promise<HttpResponse> {
return ok({message: 'hello word'})
}
}
好的:返回:
export const ok = (data: any): HttpResponse => ({
statusCode: 200,
body: data
})
测试:
describe("Hello word Controller ", () => {
it("should receive a string with name: hello, and value: hello word", () => {
const logger = new adptLogger({})
const hellowordController = new HelloWordController(logger)
expect(hellowordController.handle({hello: 'hello word'})).toEqual(ok)
});
});
我失败了:
Expected: [Function ok]
Received: {}
7 | const logger = new adptLogger({})
8 | const hellowordController = new HelloWordController(logger)
> 9 | expect(hellowordController.handle({hello: 'hello word'})).toEqual(ok)
| ^
10 | });
11 | });
已编辑:
describe("Hello word Controller ", () => {
let controller = {} as HelloWordController;
let logger: adptLogger = {} as adptLogger;
beforeEach(() => {
logger = new adptLogger({});
controller = new HelloWordController(logger);
});
afterEach(() => {
jest.restoreAllMocks();
});
it("should receive a string with name: hello, and value: hello word", async () => {
const expedtedReturn = {
statusCode: 200,
body: { message: "hello word" },
};
expect(await controller.handle({ hello: "hello word" })).toEqual(
expedtedReturn
);
});
it("should receive a bad string, and receive a bad request", async () => {
const expedtedError = {
statusCode: 400,
body: new Error(`bad Request`),
};
expect(await controller.handle({ hello: "aaa" })).toEqual(expedtedError);
});
});
【问题讨论】:
-
handle是async。你需要await它。 -
@Christian 我的错谢谢你。
标签: node.js typescript jestjs