首页 > 解决方案 > 开玩笑的单元测试“期望模拟函数最后被调用,但没有被调用”

问题描述

我是 Jest 单元测试的新手,我尝试编写一个测试,但它一直说'expected mock function to have been called last with, but it was not called'不确定问题出在哪里。下面是我编写了一个 API 调用的 APIClient.js 文件,在测试文件中我模拟了数据,它记录了

Expected mock function to have been last called with: 

["/.../test1/...", {"argu4": "test4", "argu5": "test5", "name": [{"argu3": "test3"}, "argu2": "test2"]}, {"headers": {"Content-Type": "application/json", "guest": false, "locale": 'US'}}}]

but it was not called. 

APIClient.js

const { getLeapFrogHeaders } = require('...');

async myFunc(argu1, argu2, argu3, argu4, argu5) {
 const header = getLeapFrogHeaders();
 const requestBody = {
  name: [{ argu2, argu3}],
  argu4,
  argu5
 }

const response = await this.connector.patch(`/.../${argu1}/...`, requestBody, { headers });
return response.data;
}

APIClient.test.js

import APIClient from './';
import MockConnector from './';

const mockConnector = new MockConnector({});
const APIClient = new APIClient(mockConnector);

describe('APIClient test', () => {
 const headers = {
  'Content-Type' : 'application/json',
   guest: false,
   locale: 'US'
 };

 it('successfully create API', () =>{
  const requestBody = {
      name: [{ argu2: 'test2', argu3: 'test3'}],
      argu4: 'test4',
      argu5: 'test5'
     };
  const argu1 = 'test1';
  const spy = jest.spyOn(mockConnector, 'post');
  getLeapFrogHeaders.mockImplementation(() => headers);
  APIClient.myFunc(argu1, 'test2', 'test3', 'test4', 'test5');
  expect(spy).toHaveBeenLastCalledWith(`/.../${argu1}/...`, requestBody, { headers })

})
})

标签: javascriptreactjsunit-testingjestjs

解决方案


推荐阅读