En el siguiente ejemplo, token.test.ts carga un dispositivo de prueba en this.token dentro de beforeEach , para reutilizarlo dentro de los ganchos en token.behavior.ts .
// token.test.ts import { shouldBehaveLikeToken } from './token.behavior'; describe("TokenTest", function () { beforeEach('reload token fixture', async function () { ({ token: this.token }) = await loadFixture(); }); shouldBehaveLikeToken(); // More behavioral test suites }); // token.behavior.ts export function shouldBehaveLikeToken(): void { describe('balanceOf', function () { it('returns the correct balance', async function() { expect(await this.token.balanceOf(ADDRESS).to.equal(2)); // WORKS! }); }); function balanceOf() { return this.token.balanceOf(ADDRESS); // DOES NOT COMPILE WITH THIS FUNCTION! } } Independientemente de cuán profundamente anidadas sean las afirmaciones en this.token , puedo acceder a this.token dentro de Mocha hooks ( describe() / it() ) muy bien.
Sin embargo, si creo una función de ayuda que usa this.token para hacer que las pruebas sean más componibles dentro del conjunto de pruebas, aparece el error de que 'this' implicitly has type 'any' because it does not have a type annotation y An outer value of 'this' is shadowed by this container . Esto sucede independientemente de si se trata de una función de flecha o no, e independientemente de dónde se defina la función.
¿Alguien puede explicar lo que está pasando? ¿Cómo puedo hacer una función de ayuda que use el preservado this del bloque beforeEach ?
Parece que su función externa balanceOf requiere que this contexto sea el de Mocha.Context que solo está disponible dentro de una prueba de Mocha. Debe especificar this tipo de su función balanceOf , luego vincular la función al contexto Mocha.Context explícitamente así:
export function shouldBehaveLikeToken(): void { describe('balanceOf', function () { it('returns the correct balance', async function() { // It is only within this callback that your `this` context is `Mocha.Context`. // The context will not carry over outside of the callback. expect(await balanceOf.bind(this)().to.equal(2)); // Bind the function here. }); }); function balanceOf(this: Mocha.Context) { // explicit `this` type here. return this.token.balanceOf(ADDRESS); } } La razón por la que su primera función balanceOf no puede escribir this correctamente es porque todas las declaraciones de función (funciones creadas con la palabra clave function ) vincularán window o global de forma predeterminada, o undefined si está en modo estricto. Puede leer más sobre cómo las funciones enlazan su contexto aquí this