Jest.js 使用ts-mockito在Typescript中模拟对象的问题

mdfafbf1  于 2023-05-04  发布在  Jest
关注(0)|答案(1)|浏览(208)

当我尝试使用mockito-ts在模拟对象的示例上模拟成员函数的返回值时,我发现成员函数不是函数。
TypeError: Cannot read properties of null (reading 'methodStubCollection')
当我在我正在进行的更大的项目中运行这个时,我有一个不同的消息表明有类似的问题。mockObject.mockMethod is not a function
this question和其他人强调instance调用是关键的,我认为我做得对。但我还是看到了问题。
下面是最小可复制代码示例:
package.json:

{
  "name": "dwf_backend",
  "version": "1.0.0",
  "description": "Server for DrawWithFriends app",
  "main": "index.js",
  "scripts": {
    "test": "jest --coverage",
    "dev": "concurrently \"npx tsc --watch\" \"nodemon -q dist/server.js\"",
    "start": "ts-node src/index.ts"
  },
  "author": "TJ",
  "license": "ISC",
  "devDependencies": {
    "@types/jest": "^29.5.1",
    "jest": "^29.5.0",
    "ts-jest": "^29.1.0",
    "ts-mockito": "^2.6.1"
  }
}

test/mockito_test.test.ts:

import { mock, instance, anything, when } from 'ts-mockito'

class B {
    public doTheThing(str: string): number {
        return str.length;
    }
}

class A {
    private readonly b: B;
    constructor(b: B) {
        this.b = b;
    }

    public doTheMainThing() {
        this.b.doTheThing('strrr');
    }
}

describe('test cases', () => {
    it('passes', () => {
    });

    it('mocks', () => {
        const mockedB: B = mock(B);

        const a = new A(instance(mockedB));
        a.doTheMainThing();
    });

    it('controls the mocked method', () => {
        const mockedB: B = mock(B);

        const instanceB: B = instance(mockedB);
        console.log(`instanceB is: ${JSON.stringify(instanceB)}`);

        when(instanceB.doTheThing(anything())).thenReturn(4);

        const a = new A(instanceB);
        a.doTheMainThing();
    });
});

运行npm run test

k3bvogb1

k3bvogb11#

从Stubbing方法调用doc,我们应该将mock函数返回的模拟对象(而不是instance函数返回的示例对象)传递给stub方法及其返回值。
它应该是:

const mockedB: B = mock(B);
const instanceB: B = instance(mockedB);
when(mockedB.doTheThing(anything())).thenReturn(4);

不是

const mockedB: B = mock(B);
const instanceB: B = instance(mockedB);
when(instanceB.doTheThing(anything())).thenReturn(4);

一个工作示例:

import { mock, instance, anything, when } from 'ts-mockito'

class B {
  public doTheThing(str: string): number {
    return str.length;
  }
}

class A {
  private readonly b: B;
  constructor(b: B) {
    this.b = b;
  }

  public doTheMainThing() {
    return this.b.doTheThing('strrr');
  }
}

describe('test cases', () => {
  it('controls the mocked method', () => {
    const mockedB: B = mock(B);
    const instanceB: B = instance(mockedB);
    when(mockedB.doTheThing(anything())).thenReturn(4);

    const a = new A(instanceB);
    const actual = a.doTheMainThing();
    expect(actual).toBe(4);
  });
});

测试结果:

PASS  stackoverflow/76133872/index.test.ts
  test cases
    ✓ controls the mocked method (2 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.665 s, estimated 1 s

相关问题