【发布时间】:2021-10-15 22:54:58
【问题描述】:
在下面的示例中,token.test.ts 将测试夹具加载到 beforeEach 内的 this.token 中,以便在 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!
}
}
不管this.token 上的嵌套断言有多深,我都可以在 Mocha 挂钩(describe()/it())中访问this.token。
但是,如果我创建一个使用 this.token 的帮助函数来使测试在测试套件中更加可组合,我会得到 'this' implicitly has type 'any' because it does not have a type annotation 和 An outer value of 'this' is shadowed by this container 的错误。不管它是否是箭头函数,也不管函数是在哪里定义的,都会发生这种情况。
有人可以解释发生了什么吗?如何创建一个使用 beforeEach 块中保留的 this 的辅助函数?
【问题讨论】:
标签: javascript typescript mocha.js