伙计们在测试 NestJS 应用程序时陷入困境,该应用程序具有带有提供程序的控制器,该应用程序通过 websockets 连接到某些 api
test.module.ts
import { Module, Global } from '@nestjs/common'
import { TestService } from './test.service'
import { TestController } from './test.controller'
@Global()
@Module({
imports: [],
providers: [TestService],
controllers: [TestController]
})
export class TestModule {}
test.controller.ts
import { Controller, Get } from '@nestjs/common'
import { TestService } from './test.service'
@Controller('test')
export class TestController {
constructor(private readonly testService: TestService) {}
@Get('/dictionaries')
async getDictionaries(): Promise<{ status: boolean }> {
return { status: true }
}
}
test.service.ts
import { Injectable } from '@nestjs/common'
import { client as WebSocketClient } from 'websocket'
import cas from 'ssl-root-cas'
import HttpsProxyAgent from 'https-proxy-agent'
import https from 'https'
import 'source-map-support/register' // source map
interface CaList extends Buffer {
addFile(file: string): Buffer[]
}
@Injectable()
export class TestService {
public client: WebSocketClient | null = null
constructor() {
this.init()
}
init(): void {
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'
this.client = new WebSocketClient()
const token = process.env.TOKEN
const KtUrl = `wss://my.host/ws/v2/?app_id=123456&token=${token}`
const caList = cas.create() as CaList
const path = process.env.PROJECT_PATH
caList.addFile(path + 'certs/cert1-chain.crt')
caList.addFile(path + 'certs/cert2-chain.crt')
this.client.connect(KtUrl, undefined, undefined, undefined, {
agent: new https.Agent({
ca: caList
})
})
//this.client.connect(KtUrl, undefined, undefined, undefined)
this.client.on('connectFailed', (e) => {
console.log(e)
})
}
}
test.controler.spec.ts
import { Test, TestingModule } from '@nestjs/testing'
import { TestController } from './test.controller'
import { TestService } from './test.service'
jest.useFakeTimers()
describe('TestController and ktIotService', () => {
let ktIotController: TestController
let ktIotService: TestService
let app: TestingModule
beforeEach(() => {
jest.useFakeTimers()
})
beforeAll(async () => {
app = await Test.createTestingModule({
controllers: [TestController],
providers: [TestService],
imports: []
}).compile()
ktIotController = app.get<TestController>(TestController)
ktIotService = await app.get<TestService>(TestService)
})
afterAll(() => {
app.close()
})
describe('test methods.ts', () => {
it('test onApplicationShutdown', async () => {
expect(1).toEqual(1)
})
})
})
不得不提的是,为了在开发模式下连接到主机,我必须 连接证书添加代理和ca或使用dirty hack process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'
但是在测试期间,第一个选项和第二个选项都不起作用,因此在与代理和 cas 连接时出现此错误
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
at Object.createBufferingLogger [as BufferingLogger] (../node_modules/websocket/lib/utils.js:24:23)
at new WebSocketConnection (../node_modules/websocket/lib/WebSocketConnection.js:42:25)
at WebSocketClient.Object.<anonymous>.WebSocketClient.succeedHandshake (../node_modules/websocket/lib/WebSocketClient.js:343:22)
at WebSocketClient.Object.<anonymous>.WebSocketClient.validateHandshake (../node_modules/websocket/lib/WebSocketClient.js:332:10)
at ClientRequest.handleRequestUpgrade (../node_modules/websocket/lib/WebSocketClient.js:261:14)
/home/ilik/Documents/IOT/Smart Metering/node_modules/websocket/lib/utils.js:24
var logFunction = require('debug')(identifier);
^
TypeError: require(...) is not a function
at Object.createBufferingLogger [as BufferingLogger] (/home/ilik/Documents/IOT/Smart Metering/node_modules/websocket/lib/utils.js:24:39)
at new WebSocketConnection (/home/ilik/Documents/IOT/Smart Metering/node_modules/websocket/lib/WebSocketConnection.js:42:25)
或连接 NODE_TLS_REJECT_UNAUTHORIZED 时出现此错误
Error: unable to verify the first certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1497:34)
at TLSSocket.emit (events.js:315:20)
at TLSSocket._finishInit (_tls_wrap.js:932:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:706:12) {
code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'
}
据我了解 process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0' 在开发模式下工作正常,但在测试期间用玩笑它不起作用所以我得到错误,所以要么我应该将证书连接到 websocket 工作,以便开玩笑不会抱怨或使其使用 NODE_TLS_REJECT_UNAUTHORIZED。
jest.useFakeTimers() 已经试过了,没用 任何建议请