用Jest测试时获取TypeError

时间:2019-06-13 19:06:33

标签: node.js unit-testing jestjs ts-jest

我正在尝试测试利用Auth0 NodeJs库的功能,但在模拟该库后却遇到TypeError。任何帮助/指针/方向表示赞赏。

我尝试过开玩笑的​​文档中所述的多个示例,还尝试了一些在网上找到的示例,但我似乎没有。

//auth0.provider.ts

import { ManagementClient } from 'auth0';
import { conf } from '../config'
import { User } from '../model/user.model';

var management = new ManagementClient({
    token: conf.idp.auth0_client_id,
    domain: conf.idp.auth0_domain
});

const create = async (user: User) => {
    let resp = await management.createUser({
        username: user.username,
        email: user.email,
        given_name: user.first_name,
        family_name: user.last_name,
        name: user.first_name + ' ' + user.last_name,
        phone_number: user.phone_number,
        phone_verified: true,
        verify_email: true, // sends email verification??? Need to be tested.
        password: '', // TBD
        connection: "Initial-Connection"

    });

    return resp;
}

export = { create }
// auth0.test.ts

import { ManagementClient } from "auth0";
import { conf } from "../../src/config";
import Auth0Provider from "../../src/provider/auth0.provider";
import { User } from "../../src/model/user.model"

jest.mock('auth0');

const mockCreateUser = jest.fn(() => {
    return { given_name: 'John', family_name: 'Doe' }
});
//const MockManagementClient = jest.fn(() => {
//    createUser: mockCreateUser
//});
const MockManagementClient = jest.fn();

(ManagementClient as any).mockImplementation(() => MockManagementClient);
const management = new ManagementClient({
    token: conf.idp.auth0_client_id,
    domain: conf.idp.auth0_domain
});
management.createUser = jest.fn();

const user: User = { 
    first_name: 'John', 
    last_name: 'Doe',
    email: 'tester@gmail.com',
    phone_number: '14162248877'
};

describe('[Auth0 Management API]', () => {
    test('User is successfully created in Auth0', async () => {

        let resp = await Auth0Provider.create(user);
        expect(typeof resp).toEqual('object');
        expect(management.createUser).toHaveBeenCalledTimes(1);
    })
});

我希望对“ management.createUser” 进行模拟,但会收到以下错误。

TypeError: management.createUser is not a function

  at Object.<anonymous> (src/provider/auth0.provider.ts:692:47)
  at src/provider/auth0.provider.ts:663:38
  at Object.<anonymous>.__awaiter (src/provider/auth0.provider.ts:601:10)
  at Object.create (src/provider/auth0.provider.ts:687:10)
  at Object.<anonymous> (tests/unit/auth0.test.ts:43:40)
  at tests/unit/auth0.test.ts:7:71
  at Object.<anonymous>.__awaiter (tests/unit/auth0.test.ts:3:12)
  at Object.test (tests/unit/auth0.test.ts:40:62)

0 个答案:

没有答案