【问题标题】:Jest Mock + Typescript error TS2339Jest Mock + Typescript 错误 TS2339
【发布时间】:2018-09-10 20:55:58
【问题描述】:

我正在typescript 中构建一个Express 服务器,我想使用jest 作为我的测试框架。

根据例子,我在网上看到如果要mock下面的类方法:

// src/orig.ts
export class Orig {
    static testFunc() {
        return 'orig';
    }
}

我需要创建以下文件:

// src/__mocks__/orig.ts
export class Orig {
    static __fake: string = 'fake';
    static testFunc() {
        return Orig.__fake;
    }
}

app.js 看起来像这样:

const app = require('express')();
const { Orig } = require('./src/Orig');

app.get('/', (req, res) => { res.send(Orig.testFunc()); });

module.exports = app.listen(3000);

我的测试文件应该是这样的:

// tests/test.ts
const request = require('supertest');
const app = require('../app');

import { Orig } from '../src/Orig';

jest.mock('../src/Orig');

describe('Test the mock', () => {
    test('It should return the fake string', () => {
        Orig.__fake = 'a fake string';
        return request(app).get('/').then(response => {
            expect(response.statusCode).toBe(200);
            expect(response.body).toEqual('a fake string');
        });
    });
});

我的问题是我收到以下错误:

error TS2339: Property '__fake' does not exist on type 'typeof Orig'

如何忽略/解决此问题?还是有更好的方法在我的项目中进行模拟?

谢谢!

【问题讨论】:

    标签: typescript express jestjs


    【解决方案1】:

    目前,我使用了以下解决方法: 而不是打电话给Orig.__fake,我打电话给Orig['__fake']。 这不是我想要的,但它确实有效。

    【讨论】:

      猜你喜欢
      • 2018-09-08
      • 2021-05-26
      • 2019-12-12
      • 2018-01-14
      • 1970-01-01
      • 2020-03-12
      • 2021-02-25
      • 2020-05-04
      • 2021-06-01
      相关资源
      最近更新 更多