当我尝试使用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
1条答案
按热度按时间k3bvogb11#
从Stubbing方法调用doc,我们应该将
mock
函数返回的模拟对象(而不是instance
函数返回的示例对象)传递给stub方法及其返回值。它应该是:
不是
一个工作示例:
测试结果: