[英]Jest error TypeError: (0 , _jest.test) is not a function
[英]JEST error TypeError: specificMockImpl.apply is not a function
尝试使用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);
});
});
}
还有其他方法可以在开玩笑中模拟功能吗? 我读过一篇文章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);
});
最好不要试图改变其他地方使用的const
。
您可以更改getTokensWithAuthCode
以使其接收sdk
作为参数,因此在您的测试中,您将传递模拟函数作为参数,因此具有比直接变异sdk
更可预测的行为。
在您的代码中,您可以使用签名getTokensWithAuthCodeUnbound(sdk)
进行第二次getTokensWithAuthCode
实现,然后将其导出。 此实现将用于您的测试。
使用相同的getTokensWithAuthCode
名称导出,您可以调用:
export const getTokensWithAuthCode = getTokensWithAuthCodeUnbound.bind(null, sdk)
这样一来,您的应用程序将使用getTokensWithAuthCodeUnbound
绑定默认的sdk
,并且可以测试更容易实施。
Mozilla开发人员网络(MDN) bind
文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.