我正在为一个简单的应用程序使用节点并进行超级测试。我为本地测试数据库安装了SQlite3。我做了一个简单的测试,将超级插入数据库。我想在每次运行测试时重置数据库。我正在寻找文档,但似乎找不到它。我想在这里问一下,因为似乎有人很可能会知道该信息。
const request = require('supertest');
const server = require('../server');
describe('Authentication', function() {
//database reset here
it('should create a new user /users/registration', function(done) {
request(server)
.post('/users/register')
.send({
username: 'user-name',
email: '[email protected]',
password: '12345'
})
.set('Accept', 'application/json')
.expect(201, done);
});
});
所以最好的方法是在Api的路由功能中包含一些逻辑
Receive an API request
Check if ['X-MOCK-HEADER'] exists
If it does then route to the mock version of the endpoint
因此您的用于创建用户的模拟将始终返回201 OK-您的模拟端点将执行以下操作:
const routes = {
CREATE_USER_OK:() => { return {....} } // make sure these return proper http responses
CREATE_USER_BAD_REQUEST: () { return {...} }
}
return routes[HEADER_VALUE]()
原因是在这种情况下您正在测试路由而不是数据库类,所以您只想返回静态数据,如果您想测试其他内容,只需将X-MOCK-HEADER值更改为所需的值并添加返回正确的http响应/代码的模拟路线-我需要知道API代码在后端实现上对您有什么帮助。
如果可能的话,不要弄乱暂存数据库进行测试,因为在以后的过程中,随着它逐渐充满垃圾,您将遭受很多痛苦。
此外,如果您使用的是前端应用程序,则可以快速使用静态数据进行原型制作-如果您有一个前端团队正在等待API端点说要创建登录屏幕,则这特别有用。
没有重置sqlite数据库的明确方法,只需删除该数据库然后重新创建。
如果要在每次测试前运行任何代码,都可以在beforeEach中使用jest
函数
describe('my test', () => {
beforeEach(() => {
// code to run before each test
});
test('test 1', () => {
// code
});
test('test 2', () => {
// code
});
});
我在文件中做过,并且工作正常
const request = require('supertest');
const server = require('../server');
const knex = require('knex');
const dbConfig = require('../knexfile.js')['test'];
const db = knex(dbConfig);
describe('Authentication', () => {
beforeEach(async () => {
await db('users').truncate();
});
it('should create a new user /users/registration', function(done) {
request(server)
.post('/users/register')
.send({
username: 'user-name',
email: '[email protected]',
password: '12345'
})
.set('Accept', 'application/json')
.expect(201, done);
});
});