是否可以使用jest spyOn获取原始函数的返回值?

时间:2019-12-11 06:06:23

标签: node.js typescript jestjs

我已经在函数( buildSearchParameter )中使用了spyOn来验证toBeCalledWith()。我还需要获取该间谍函数的返回值,以将其传递给params中的另一个函数( readAll )。那么有什么方法可以从间谍函数获取返回值?

    search = async (query: Request['query'], endpointConstants: EndpointConstantsType<ModelType>): Promise<ModelType[] | ValidationError | ResponseErrorMessageType> => {
        const searchParam = ModelUtility.buildSearchParameter(
            query,
            endpointConstants,
            this.schemaConstants
        );
        // check for unknown fields
        const isUnknownFields = ModelUtility.isUnknownFields<ModelType>(EndpointType.SEARCH, <ModelType>searchParam, this.schemaConstants);
        if (isUnknownFields) {
            return <ResponseErrorMessageType>this.errorConstants.invalidQueryParameters;
        }
        return this.readAll(query, searchParam, endpointConstants);
    };

sample.test.ts

it('should return matched document when query parameter is valid', async () => {
        // Preparing
        const query = { name: 'muthu' };
        const queryStatus = { name: 'muthu'};
        const buildSearchParameterSpy = jest.spyOn(ModelUtility, 'buildSearchParameter')
        const isUnknownFieldsSpy = jest
            .spyOn(ModelUtility, 'isUnknownFields')
            .mockReturnValueOnce(false);
        // Executing
        const result = await loadConstants.search(query, endpointConstants);
        expect(buildSearchParameterSpy).toBeCalledWith(query, endpointConstants, loadConstants.m3SchemaConstants.product_brand);
        expect(isUnknownFieldsSpy).toBeCalledWith('search', { product_brand_name: 'muthu' }, loadConstants.m3SchemaConstants.product_brand);
    });

0 个答案:

没有答案