我正在尝试使用开玩笑来模拟Typescript类中的导入类,以下代码用于主程序(我从函数内部删除了一些代码,但仍应清楚我要做什么)

import * as SocketIO from "socket.io";

import {AuthenticatedDao} from "../../dao/authenticated.dao";

export default class AuthenticationService {
    private readonly _authenticatedDao: AuthenticatedDao = AuthenticatedDao.Instance;
    private readonly _io;

    constructor(socketIo: SocketIO.Server) {
        this._io = socketIo;
    }

    public authenticateUser(username: string, password: string, clientSocketId: string): void {
        this._authenticatedDao.authenticateUser(username, password).then((authenticatedUser) => {

        }).catch(rejected => {

        });
    }
}


import {createServer, Server} from 'http';
import * as express from 'express';
import * as socketIo from 'socket.io';
import {LogincredentialsDto} from "./models/dto/logincredentials.dto";
import {config} from './config/config';
import AuthenticationService from "./services/implementation/authentication.service";
import {Logger} from "./helperclasses/logger";
import {format} from "util";

export class ClassA {
    private readonly _configPort = config.socketServerPort;

    private readonly _logger: Logger = Logger.Instance;
    private _app: express.Application;
    private _server: Server;
    private _io: socketIo.Server;
    private _socketServerPort: string | number;
    private _authenticationService: AuthenticationService;


    constructor() {
        this.configure();
        this.socketListener();
    }

    private configure(): void {
        this._app = express();

        //this._server = createServer(config.sslCredentials, this._app);
        this._server = createServer(this._app);

        this._socketServerPort = process.env.PORT || this._configPort;
        this._io = socketIo(this._server);

        this._server.listen(this._socketServerPort, () => {
            this._logger.log(format('Server is running on port: %s', this._socketServerPort));
        });

        this._authenticationService = new AuthenticationService(this._io);
    }


    private socketListener(): void {
        this._io.on('connection', (client) => {
                client.on('authenticate', (loginCreds: LogincredentialsDto) => {
                    console.log(loginCreds.username, loginCreds.password, client.id);
                    this._authenticationService.authenticateUser(loginCreds.username, loginCreds.password, client.id);
                });
            }
        );
    }
}

我正在尝试在“AuthenticationService”中模拟函数“authenticateUser”,而不是调用我要模拟promise的普通代码。我尝试使用https://jestjs.io/docs/en/es6-class-mocks中提供的示例,但是在尝试执行以下操作时:
import AuthenticationService from '../src/services/implementation/authentication.service';
jest.mock('./services/implementation/authentication.service');

beforeEach(() => {
    AuthenticationService.mockClear();
});

it('test', () => {

    // mock.instances is available with automatic mocks:
    const authServerInstance = AuthenticationService.mock.instances[0];

我收到此错误:
错误:(62、31)TS2339:类型“AuthenticationService”类型上不存在属性“模拟”。

我在这里做错了什么?因为使用了promises,我是否应该以不同的方式 mock 类/函数?

最佳答案

问题
AuthenticationService的键入不包含mock属性,因此TypeScript会引发错误。

细节
jest.mock创建模块的automatic mock,该模块“用模拟构造函数替换ES6类,并用总是返回undefined的模拟函数替换其所有方法”。

在这种情况下,defaultauthentication.service.ts导出是ES6类,因此将其替换为模拟构造函数。

模拟构造函数具有mock属性,但是TypeScript不知道该属性,并且仍将AuthenticationService视为原始类型。

解决方案

使用jest.Mocked让TypeScript知道jest.mock引起的打字变化:

import * as original from './services/implementation/authentication.service';  // import module
jest.mock('./services/implementation/authentication.service');

const mocked = original as jest.Mocked<typeof original>;  // Let TypeScript know mocked is an auto-mock of the module
const AuthenticationService = mocked.default;  // AuthenticationService has correct TypeScript typing

beforeEach(() => {
  AuthenticationService.mockClear();
});

it('test', () => {

    // mock.instances is available with automatic mocks:
    const authServerInstance = AuthenticationService.mock.instances[0];

关于typescript - 用玩笑 mock 导入的 typescript 中的类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53502054/

10-11 09:29
查看更多