我正在为使用浏览器WebAPI接口的类编写单元测试。
我使用ts-mockito来模拟接口(在我的例子中是WebGL2RenderingContext )。
当我运行测试时,Node抛出ReferenceError: WebGL2RenderingContext is not defined,这是可以理解的,因为测试是在NodeJS环境下运行的,而不是在浏览器下运行的,因此类/接口不存在。
有没有办法让NodeJS环境知道WebAPI接口,这样就可以被模拟了吗?
注意到:因为它是一个单元测试,所以它不应该在真正的浏览器上运行。
jsdom似乎是一个可能的解决方案,但我不知道如何用ts来嘲弄它。
下面的片段说明了我要做的事情:
import { mock, instance, verify } from 'ts-mockito'
// ========== CLASS ==========
class DummyClass {
dummyMethod() : void {}
}
class TestedClass {
static testDummy(dummy : DummyClass) : void {
dummy.dummyMethod();
}
static testGlCtx(glCtx : WebGL2RenderingContext) : void {
glCtx.flush();
}
}
// ========== TEST ==========
describe('DummyClass', () => {
// This test passed successfully
it('works fine', () => {
const mockDummy = mock(DummyClass);
TestedClass.testDummy( instance(mockDummy) );
verify( mockDummy.dummyMethod() ).once();
});
});
describe('WebGL interface', () => {
it('works fine', () => {
// This line failed with 'ReferenceError: WebGL2RenderingContext is not defined'
const mockGLCtx = mock(WebGL2RenderingContext);
TestedClass.testGlCtx( instance(mockGLCtx) );
verify( mockGLCtx.flush() ).once();
});
});使用mocha命令mocha --require ts-node/register 'test.ts'运行。
发布于 2020-12-11 15:38:22
有两种解决方案:通用DOM API和通用模拟。
对于常见的DOM
正如本StackOverflow答案中详细介绍的那样,jsdom可用于将DOM引入NodeJS运行时环境。
运行npm install --save-dev jsdom global-jsdom
并将Mocha的命令改为
mocha --require ts-node/register --require global-jsdom/register 'test.ts'此解决方案适用于常见的DOM (如HTMLElement、SVGElement、File),
但它不适用于更专业的API (WebGL、Crypto、音频和视频)。
用于通用接口模拟
原来是ts-mockito 有一种模拟接口的方法,包括DOM &任何浏览器Web。
因此,可以将上述测试代码更改为:
describe('WebGL interface', () => {
it('works fine', () => {
const mockGLCtx = mock<WebGL2RenderingContext>();
TestedClass.testGlCtx( instance(mockGLCtx) );
verify( mockGLCtx.flush() ).once();
});
});测试将成功运行。
https://stackoverflow.com/questions/65249130
复制相似问题