我有一个正文
// index.ts
import { createConnection } from "typeorm";
createConnection().then(async connection => {
// express app code here
}).catch(error => console.log(error));现在,我想使用jest编写单元测试用例,并且我希望连接可以跨测试可用。
// abc.test.ts
createConnection().then(async connection => {
describe('ABC controller tests', () => {
it('should test abc function1', async () => {
// test body does here
});
});
}).catch(error => console.log(error));我有几点担心:
SyntaxError: Cannot use import statement outside a moduleindex.ts这样的测试,没有入口点。如何在单元测试中全局使用createConnection()和TypeORM?
发布于 2020-06-06 06:02:37
您应该使用beforeEach和afterEach来设置状态/上下文/世界。类似于:
describe('ABC controller tests', () => {
let connection: Connection
beforeEach(async () => {
connection = await createConnection()
})
it('should test abc function1', async () => {
connection.doSomething()
})
afterEach(async () => {
await connection.close()
})
})发布于 2020-06-06 06:06:33
你应该能够
jest.setup.js(setupFilesAfterEnv)
// Promise<Connection>
global.connection = createConnection()然后你可以等待承诺在你的测试中被解决。
abc.test.ts
describe('abc', () => {
beforeAll(async () => {
await global.connection
});
it('should be connected', () => {
// not sure if that property really exists
expect(global.connection).toHaveProperty('isConnected', true)
})
})https://stackoverflow.com/questions/62227913
复制相似问题