问题
Take the following code snippet:
import { Foo } from "./foo";
export interface MyContext extends Mocha.Context {
foo: Foo;
}
This is in a project with the @types/mocha package installed, so that the Mocha
namespace can be inferred by the compiler.
Now, if I try to use this interface in a test suite:
import { MyContxt } from "../types/mocha";
describe("my test suite", function() {
it("should do something", function(this: MyContext) {
...
});
});
The TypeScript compiler throws the following error:
No overload matches this call.
I looked up the source code, and it seems that mocha expects any function passed to the before
, beforeEach
, it
, etc., hooks to be linked to a Context
type as defined in @types/mocha
- it doesn't accept any descendant types.
How can I go around this and extend the Mocha Context interface in my testing environment?
回答1:
Literally extending mocha's Context
type using that derived interface is not what you want to do here. Instead, you want to augment the type defined by the library, adding your member.
This can be accomplished as follows:
// augmentations.d.ts
import {Foo} from './foo';
declare module "mocha" {
export interface Context {
foo: Foo;
}
}
Example usage:
describe("my test suite", function() {
it("should do something", function() {
console.log(this.foo);
});
});
来源:https://stackoverflow.com/questions/62282408/how-to-extend-mochas-context-interface