gpt4 book ai didi

javascript - JEST 错误 TypeError : specificMockImpl. apply is not a function

转载 作者:数据小太阳 更新时间:2023-10-29 06:09:40 29 4
gpt4 key购买 nike

尝试使用来自 api 的回调来模拟其中一个函数并得到错误 TypeError: specificMockImpl.apply is not a function

import { IEnvironmentMap, load } from 'dotenv-extended';
import { getTokensWithAuthCode, sdk } from '../src/connection-manager';

describe('getTokensWithAuthCode function Tests', () => {

jest.useFakeTimers();
let boxConfig: IEnvironmentMap;

beforeAll(() => {
boxConfig = load({
errorOnMissing: true,
});
});

it('should reject a promise if there is wrong auth code provided', async () => {

sdk.getTokensAuthorizationCodeGrant = jest.fn().mockImplementation(boxConfig.BOX_AUTH_CODE, null, cb => {
cb('Error', null);
});

try {
const tokens = await getTokensWithAuthCode();
} catch (error) {
expect(error).toBe('Error');
}
});
});

我正在尝试测试的功能如下:

import * as BoxSDK from 'box-node-sdk';
import { IEnvironmentMap, load } from 'dotenv-extended';
import {ITokenInfo} from '../typings/box-node-sdk';

const boxConfig: IEnvironmentMap = load({
errorOnMissing: true,
});

export const sdk: BoxSDK = new BoxSDK({
clientID: boxConfig.BOX_CLIENT_ID,
clientSecret: boxConfig.BOX_CLIENT_SECRET,
});

/**
* - Use the provided AUTH_CODE to get the tokens (access + refresh)
* - Handle saving to local file if no external storage is provided.
*/
export async function getTokensWithAuthCode() {

return new Promise((resolve: (tokenInfo: ITokenInfo) => void, reject: (err: Error) => void) => {

if (boxConfig.BOX_AUTH_CODE === '') {
reject(new Error('No Auth Code provided. Please provide auth code as env variable.'));
}

sdk.getTokensAuthorizationCodeGrant(boxConfig.BOX_AUTH_CODE, null, (err: Error, tokenInfo: ITokenInfo) => {
if (err !== null) {
reject(err);
}

resolve(tokenInfo);
});
});
}

有没有其他方法可以在 Jest 中模拟函数?我看过一篇文章https://www.zhubert.com/blog/2017/04/12/testing-with-jest/

最佳答案

在这一行中,不是将函数传递给 mockImplementation,而是传递三个参数:

jest.fn().mockImplementation(boxConfig.BOX_AUTH_CODE, null, cb => {
cb('Error', null);
});

看起来您可能刚刚错过了一些牙套。尝试将其切换为:

jest.fn().mockImplementation((boxConfig.BOX_AUTH_CODE, null, cb) => {
cb('Error', null);
});

关于javascript - JEST 错误 TypeError : specificMockImpl. apply is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48231169/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com