开玩笑的模拟子模块功能

时间:2019-02-22 15:32:07

标签: node.js express testing mocking jestjs

我有一个名为client的节点模块。它具有以下结构:

//index.js
import users from "./users"

export default { users }

并且:

//users.js
export default { getUser }
function getUser(username) {
    ...
    return {role: userRole}  
}

我想在测试中模拟此getUser(username)函数。 所以我可以这样称呼:

client.users.getUser.mockResolvedValueOnce({role: "manager"}) 

我的测试标题是:

let client = jest.genMockFromModule('client').default;
client.users.getUser = jest.fn();

但是,运行测试时,我的原始代码调用client.users.getUser时出现以下错误。

TypeError: Cannot read property 'users' of undefined

  58 | 
  59 |     // Retrieve user and then return its projects
> 60 |     client.users.getUser(username)
     |                  ^
  61 |         .then(user => {
  62 |             if (!user) {
  63 |                 throw new Error(`User ${username} not found`)

  at Object.getUser (node_modules/client/build/users.js:26:45)
  at Object.getUser [as insert] (src/web/controller/projects.js:60:18)
  at Object.insert (src/web/controller/projects.test.js:80:18)

1 个答案:

答案 0 :(得分:1)

您可以像这样模拟//users.js模块:

jest.mock('./users.js', () => ({getUser: () => ({role: "manager"})})) //note that the path is relative to the test

如果在测试期间需要不同的返回值,则可以对其进行模拟以返回间谍,并在测试中设置模拟返回值:

import {getUsers} from './users'
jest.mock('./users.js', () => ({getUser: jest.fn()})) 

it('does something', () => {
 getUser.mockImplementation(() => ({role: "manager"}))
})
it('does something else', () => {
 getUser.mockImplementation(() => ({role: "user"}))
})