javascript jest中的json-schema验证
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript jest中的json-schema验证相关的知识,希望对你有一定的参考价值。
const moment = require('moment');
const { URL_SESSION_HISTORY } = require('../../src/constants/urls');
const { STATUS_OK } = require('../../src/constants/used-http-status-codes');
const mocker = require('../../dev-helpers/testing/mocker');
const handler = mocker((req, res) =>
res.status(STATUS_OK).send({
sessions: [
{
id: 5433,
starts_at: moment()
.utc()
.subtract({
hours: 4,
minutes: 24,
seconds: 37
})
.toISOString(),
durationSeconds: moment.duration(1, 'hours').asSeconds(),
adminEdited: false
},
{
id: 567,
starts_at: moment()
.utc()
.subtract({
hours: 2,
minutes: 24,
seconds: 37
})
.toISOString(),
durationSeconds: moment.duration(1, 'hours').asSeconds(),
adminEdited: false
}
]
})
);
const sessionHistory = app => app.get(URL_SESSION_HISTORY, handler);
module.exports = { sessionHistory, handler };
const request = require('supertest');
const express = require('express');
const {matchers} = require('jest-json-schema');
const { URL_SESSION_HISTORY } = require('../../src/constants/urls');
const itTriggersEndpointHandler = require('../../dev-helpers/testing/it-triggers-endpoint-handler');
expect.extend(matchers);
describe('sessionHistory', () => {
const { sessionHistory, handler } = require('./session-history');
const app = sessionHistory(express());
itTriggersEndpointHandler(app, handler, URL_SESSION_HISTORY, `calls handler`);
it(`gives expected response`, done => {
const schema = {
properties: {
sessions: {
type: 'array',
items: {
properties: {
id: {
type: 'number'
},
starts_at: {
type: 'string',
format: "date-time"
},
durationSeconds: {
type: 'number'
},
adminEdited: {
type: 'boolean'
},
},
required: ['id', 'starts_at', 'durationSeconds', 'adminEdited']
},
},
},
required: ['sessions']
};
request(app)
.get(URL_SESSION_HISTORY)
.expect(({ text }) => {
expect(JSON.parse(text)).toMatchSchema(schema);
})
.end(done);
});
});
以上是关于javascript jest中的json-schema验证的主要内容,如果未能解决你的问题,请参考以下文章
一个文件中的测试是不是在 Jest 中并行运行?
[Jest] Test JavaScript with Jest
如何使用 Jest 模拟 JavaScript 窗口对象?
[Jest] Restore the Original Implementation of a Mocked JavaScript Function with jest.spyOn
javascript模拟导入组件与jest
从测试中自动生成文档(javascript、jest)