jest-extended
jest-extended copied to clipboard
toHaveBeenCalledBefore: Argument of type ... is not assignable to parameter of type 'Mock<any, any>'.
Bug
-
package
version: 2.0.0 -
node
version: 17.2.0 -
npm
(oryarn
) version: 8.1.4 -
jest
version: 27.5.1 -
typescript
version: 4.5.4
Relevant code or config
test.spec.ts:
import MyClass from "./MyClass";
import myFunction from "./myFunction";
jest.mock("./MyClass");
it("works", () => {
// Arrange
const param = 123;
// Act
myFunction(param); // uses MyClass
// Assert
expect(MyClass.prototype.initialize).toHaveBeenCalledBefore(
MyClass.prototype.finalize
);
});
jest.config.js
/** @type {import('@ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
resetMocks: true,
setupFilesAfterEnv: ["jest-extended/all"],
moduleNameMapper: {
"^csv-stringify/sync":
"<rootDir>/node_modules/csv-stringify/dist/cjs/sync.cjs",
},
globals: {
"ts-jest": {
isolatedModules: true,
tsConfig: "tsconfig.json",
},
},
clearMocks: true,
};
tsconfig.json:
{
"compilerOptions": {
"target": "ES2015",
"moduleResolution": "Node",
"strict": true,
"esModuleInterop": true,
"types": ["jest", "node"],
"lib": ["ESNext"]
}
}
What you did:
Run ./node_modules/.bin/tsc --noEmit -p .
to see compilation errors, or check IDE.
What happened (please provide anything you think will help):
//redacted
bla.spec.ts:66:7 - error TS2345: Argument of type '(bla:bla) => Promise<void>' is not assignable to parameter of type 'Mock<any, any>'.
Type '(bla:bla) => Promise<void>' is missing the following properties from type 'Mock<any, any>': getMockName, mock, mockClear, mockReset, and 12 more.
66 Bla.prototype.bla
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Could you put together a small reproduction?
Could you put together a small reproduction?
Sure! Here you go: https://github.com/Maxim-Mazurok/jest-extended-456-reproduction
Right, we should probably not force it to take a mock, and just something callable instead. It needs to be called with a mock tho, so maybe it's correct and you should use mocked
?
diff --git i/test.spec.ts w/test.spec.ts
index 33048b5..dd8d6f0 100644
--- i/test.spec.ts
+++ w/test.spec.ts
@@ -9,6 +9,6 @@ it("works", () => {
// Assert
expect(MyClass.prototype.initialize).toHaveBeenCalledBefore(
- MyClass.prototype.finalize
+ jest.mocked(MyClass.prototype.finalize)
);
});
That worked!
I remember seeing some SO answer that we used to have to use ts-jest and some similar helper, but then after jest got types - there was no more need for that helper. I'm not 100% sure that I recall that correctly tho, so maybe jest.mocked
is the best answer indeed, I'll leave that to your judgment, thanks for helping out!