Nest.js:来自控制器超类的属性初始化

时间:2019-09-24 10:02:05

标签: javascript typescript testing jestjs nestjs

我对Nest.js框架中的单元测试控制器有疑问。问题是创建测试模块时,控制器类中没有初始化父类的属性。

这是我正在谈论的示例代码:

import matplotlib.pyplot as plt
from ipywidgets import interactive

def f(data_nr, layer_nr):    
    xmin = 0
    xmax = 3

    fig, axs = plt.subplots(2, 2,figsize=(10,10))
    axs[0,0].minorticks_on()

    axs[0,0].plot(data[data_nr][layer_nr])
    axs[0,0].set_xlim(xmin, xmax)
    axs[0,0].set_ylim(-10, 0)
    axs[0,0].set_xlabel('x unit')
    axs[0,0].set_ylabel('Quantity_1')
    axs[0,0].grid(True)

    axs[0,1].minorticks_on()
    axs[0,1].plot(data[data_nr][layer_nr*3+1])
    axs[0,1].set_xlim(xmin, xmax)
    axs[0,1].set_ylim(-10, 0)
    axs[0,1].set_xlabel('x unit')
    axs[0,1].set_ylabel('Quantity_2')
    axs[0,1].grid(True)

    axs[1,0].minorticks_on()
    axs[1,0].plot(data[data_nr][layer_nr*3+2])
    axs[1,0].set_xlim(xmin, xmax)
    axs[1,0].set_ylim(-10, 0)
    axs[1,0].set_xlabel('x unit')
    axs[1,0].set_ylabel('Quantity_3')
    axs[1,0].grid(True)

    axs[1,1].minorticks_on()
    axs[1,1].plot(data[data_nr][layer_nr*3+3])
    axs[1,1].set_xlim(xmin, xmax)
    axs[1,1].set_ylim(-10, 0)
    axs[1,1].set_xlabel('x unit')
    axs[1,1].set_ylabel('Quantity_4')
    axs[1,1].grid(True)

    fig.tight_layout()

    plt.show()   

interactive_plot = interactive(f, data_nr=(0, 10,1), layer_nr=(1, 10, 1))
output = interactive_plot.children[-1]
interactive_plot

这就是我创建测试的方式

export class MyController extends SomeOtherController {

    // Inherited from SomeOtherController
    async initSomeObject() {
        this.someObject = await initializeThisSomehow();
    }

    async controllerMethod(args: string) {
        // Do something
    }

}

export abstract class SomeOtherController implements OnModuleInit {

    protected someObject: SomeObject;

    async onModuleInit() {
        await this.initSomeObject();
    }

    abstract async initSomeObject(): Promise<void>;
}

现在,如果我要在开发模式下运行应用程序,则describe('MyController', () => { let module: TestingModule; let controller: MyController; let service: MyService; beforeEach(async () => { module = await Test.createTestingModule({ imports: [], controllers: [MyController], providers: [ MyService, { provide: MyService, useFactory: () => ({ controllerMethod: jest.fn(() => Promise.resolve()), }), }, ], }).compile(); controller = module.get(MyController); service = module.get(MyService); }); describe('controller method', () => { it('should do something', async () => { jest.spyOn(service, 'controllerMethod').mockImplementation(async _ => mockResult); expect(await controller.controllerMethod(mockArgs)).toBe(mockResult); }); }); }); 属性将被初始化,并且代码可以工作。但是在运行测试时,似乎测试模块没有在初始化它(因此它是未定义的)。

非常感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:1)

在每次测试之前,您需要运行以下

await module.init(); // this is where onModuleInit is called

最好关闭应用程序

afterEach(async () => await module.close());