我想为测试运行内存数据库,但是当我运行npm test
时,无法使我的应用程序连接到该数据库。
当我运行npm test
时,我得到:
Connection fails: Error: ER_ACCESS_DENIED_ERROR: Access denied for user ''@'172.21.0.1' (using password: NO)
之所以发生这种情况,是因为我没有在npm测试中设置任何env变量,但是我不想在我的测试中使用MySQL,而仅在内存数据库中使用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);
}
有什么问题的想法吗?
答案 0 :(得分:0)
我发现这种对我有用的方式
更改此:
app.dataSource(testdb);
对此:
await app.bind('datasource.config.db').to({
name: 'db',
connector: 'memory'
});
您只是将数据源的配置更改为使用本地数据库,但是仍然是相同的数据源!
确保bind的字符串与主数据源中使用的字符串相同!