【发布时间】:2025-12-18 07:20:04
【问题描述】:
我想为我的测试运行一个内存数据库,但是当我运行 npm test 时,我无法让我的应用程序连接到它。
当我运行npm test 时,我得到:
Connection fails: Error: ER_ACCESS_DENIED_ERROR: Access denied for user ''@'172.21.0.1' (using password: NO)
发生这种情况是因为我没有在 npm test 上设置任何环境变量,但我不想在我的测试中使用 MySQL,而只是一个内存数据库,这就是我所拥有的。
testdb.datasources.ts
import {juggler} from '@loopback/repository';
export const testdb: juggler.DataSource = new juggler.DataSource({
name: 'testdb',
connector: 'memory',
});
country.controller.acceptance.ts
import {Client, expect} from '@loopback/testlab';
import {MyApplication} from '../..';
import {setupApplication} from './test-helper';
import {givenEmptyDatabase} from '../helpers/database.helpers';
describe('Country Controller', () => {
let app: MyApplication;
let client: Client;
before('setupApllication', async () => {
({app, client} = await setupApplication());
});
before(givenEmptyDatabase);
// before(givenRunningApp);
after(async () => {
await app.stop();
});
it('Should count 0 countries', async () => {
const res = await client.get('/countries/count').expect(200);
//assertations
expect(res.body.count).to.equal(0);
});
});
test-helper.ts
import {MyApplication} from '../..';
import {
createRestAppClient,
givenHttpServerConfig,
Client,
} from '@loopback/testlab';
import {testdb} from '../fixtures/datasources/testdb.datasource';
export async function setupApplication(): Promise<AppWithClient> {
const app = new MyApplication({
rest: givenHttpServerConfig({host: 'localhost'}),
});
app.dataSource(testdb); // <--- Hoped this would do the job
await app.boot();
await app.start();
const client = createRestAppClient(app);
return {app, client};
}
export interface AppWithClient {
app: MyApplication;
client: Client;
}
Country 控制器只是使用 lb4 控制器创建的标准控制器。
@get('/countries/count', {
responses: {
'200': {
description: 'country model count',
content: {'application/json': {schema: countschema}},
},
},
})
async count(
@param.query.object('where', getwhereschemafor(country)) where?: where,
): promise<count> {
return await this.countryrepository.count(where);
}
有什么想法吗?
【问题讨论】:
标签: loopbackjs