如何用JavaScript模拟服务?

如何用JavaScript模拟服务?,javascript,unit-testing,jestjs,Javascript,Unit Testing,Jestjs,我的代码如下所示 const { MyClient } = require('some-service') const invokeMe = async (input1, input2) => { const client = new MyClient({ name: 'my-name' }) return await client.invoke({ input1, input2 }).catch((err) => { throw

我的代码如下所示

const { MyClient } = require('some-service')

const invokeMe = async (input1, input2) => {
  const client = new MyClient({
    name: 'my-name'
  })

  return await client.invoke({
    input1,
    input2
  }).catch((err) => {
    throw err
  })
}
这就是我所拥有的,我如何恰当地嘲弄这项服务并监视它的名称

const { MyClient } = require('some-service')

describe('test my client', () => {
  it('invoke my client', () => {
    const response = {
      data: []
    }
    expect(invokeMe('abc', '123')).resolves.toEqual(response)
    expect(MyClient).toBeCalledWith({
      input1: 'abc',
      input2: '123'
    })
  })
})
编辑:为什么下面的代码仍然调用原始函数

it('invoke my client', () => {
  const mockInvoke = jest.fn().mockImplementation(() => Promise.resolve({
    data: []
  }))
  const mockMyClient = () => {
    return { invoke: mockInvoke }
  }
  const mockSomeService = {
    MyClient: mockMyClient
  }
  jest.doMock('some-service', () => mockSomeService
  ...
})
您可以使用模拟导入的服务

例如

index.js:

const{MyClient}=require'./某些服务'; const invokeMe=异步输入1,输入2=>{ const client=new MyClient{ 姓名:'我的名字', }; 返回等待客户 .调用{ 输入1, 输入2, } .catcherr=>{ 犯错误; }; }; module.exports=invokeMe; some-service.js:

类MyClient{ 异步调用输入1,输入2{ 返回“真实响应”; } } module.exports={MyClient}; index.test.js:

const invokeMe=需要“/”; const{MyClient}=require'./某些服务'; jest.mock./一些服务,=>{ 常量mMyClient={invoke:jest.fn}; 返回{MyClient:jest.fn=>mMyClient}; }; 描述'60008679',=>{ 它“应该调用”,异步=>{ const client=新的MyClient; client.invoke.mockResolvedValueOnce“假响应”; const-actual=wait-invoke'a',b'; 预期的实际情况是“假反应”; expectMyClient.toBeCalledWith{name:'my name'}; expectclient.invoke.toBeCalledWith{input1:'a',input2:'b'}; }; 它“应该处理错误”,异步=>{ const client=新的MyClient; const mError=新错误“某些错误”; client.invoke.mockRejectedValueOnCemeror; 等待预期调用E'a',b'。拒绝。TothRowerError错误; expectMyClient.toBeCalledWith{name:'my name'}; expectclient.invoke.toBeCalledWith{input1:'a',input2:'b'}; }; }; 100%覆盖率的单元测试结果:

通过src/stackoverflow/60008679/index.test.js 11.029s 60008679 ✓ 应该调用8ms ✓ 应该处理4ms的错误 -----|-----|-----|-----|-----|----------| 文件|%Stmts |%Branch |%Funcs |%Lines |未覆盖的行| -----|-----|-----|-----|-----|----------| 所有文件| 100 | 100 | 100 | 100 || index.js | 100 | 100 | 100 | 100 || -----|-----|-----|-----|-----|----------| 测试套件:1个通过,共1个 测试:2次通过,共2次 快照:共0个 时间:12.314s
源代码:

你看过jest文档了吗?它确实谈到了模拟模块。请看,我遵循了这些示例,可能是因为解构,它不起作用,并尝试调用服务。模拟不会阻止调用原始模块。为此,您需要使用“模拟实现”