模拟被忽略,玩笑节点

问题描述 投票:0回答:1

我正在尝试通过此测试模拟数据库,但模拟似乎被忽略。我想不出这可能是什么原因?

import { jest } from '@jest/globals';

jest.mock('../database', () => ({
  insert: jest.fn().mockReturnThis(),
}));

import database from '../database';

describe('create', () => {
  test('creates an enquiry if valid', () => {
    database.insert({ email: '[email protected]' });
    expect(database.insert).toHaveBeenCalledWith({
      email: '[email protected]',
    });
  });
});

这是在带有打字稿的节点上。在运行时我收到此错误,所以我相当有信心模拟只是被忽略了:

 FAIL  models/enquiryModel.test.js
  create
    ✕ creates an enquiry if valid (2 ms)

  ● create › creates an enquiry if valid

    expect(received).toHaveBeenCalledWith(...expected)

    Matcher error: received value must be a mock or spy function

    Received has type:  function
    Received has value: [Function anonymous]

      47 |   test('creates an enquiry if valid', () => {
      48 |     database.insert({ email: '[email protected]' });
    > 49 |     expect(database.insert).toHaveBeenCalledWith({
         |                             ^
      50 |       email: '[email protected]',
      51 |     });
      52 |   });

      at Object.<anonymous> (models/enquiryModel.test.js:49:29)

jest.config.js

/** @type {import('ts-jest').JestConfigWithTsJest} **/
export default {
  testEnvironment: 'node',
  transform: {
    '^.+.tsx?$': [
      'ts-jest',
      {
        useESM: true,
      },
    ],
  },
  extensionsToTreatAsEsm: ['.ts', '.tsx'],
};
node.js typescript testing jestjs ts-jest
1个回答
0
投票

这是因为您正在导入默认导出,但模拟了命名导出。要纠正此问题,您需要将模拟对象移动到名为

default
的属性中。

import { jest } from '@jest/globals';
import database from '../database';

// Doesn't need to be above the import statement
jest.mock('../database', () => ({
  default: {
    insert: jest.fn().mockReturnThis(),
  }
}));

describe('create', () => {
  test('creates an enquiry if valid', () => {
    database.insert({ email: '[email protected]' });
    expect(database.insert).toHaveBeenCalledWith({
      email: '[email protected]',
    });
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.