Jest not.toThrowError() 在 jest.spyOn(component.methods, 'mymethod') 测试中不起作用

myn*_*101 1 javascript unit-testing jestjs nuxt.js vue-test-utils

我正在尝试对我的 Nuxt/Vue 组件方法进行测试,以检查是否存在错误。

所以我所做的就是为这个感兴趣的方法创建一个“间谍” const spyGetNumberOfResults = jest.spyOn(SearchTable.methods, 'getNumberOfResults'),然后我期待它expect(spyGetNumberOfResults).not.toThrowError(),但是我收到一个奇怪的错误,它说我感兴趣的方法中的一个变量是未定义的。这是错误:

TypeError: Cannot set property 'countLoading' of undefined

      571 |         async getNumberOfResults () {
      572 |             // Kick off loader to signal retrieving counts
    > 573 |             this.countLoading = true;
          | ^
      574 | 
      575 |             // Initialize count
      576 |             this.count = '';

      at getNumberOfResults (components/core/SearchTable.vue:573:1)
      at Object.<anonymous> (node_modules/expect/build/toThrowMatchers.js:81:11)
      at Object.toThrowError (node_modules/expect/build/index.js:342:33)
      at Object.<anonymous> (test/SearchTable.spec.js:150:57)
Run Code Online (Sandbox Code Playgroud)

这是我的测试代码:

test(`GET /${MODEL[1][MAIN_MODULES[i]].subModules[j].backEndFilters.mainModule}/${MODEL[1][MAIN_MODULES[i]].subModules[j].backEndFilters.subModule}/`, async () => {
    const API_ENDPOINT = process.env.NODE_ENV;
    // Initialize our variables
    let success = '';
    let responseData;
    let url = `${API_ENDPOINT}${store.state.core.group.current.id}/${MODEL[1][MAIN_MODULES[i]].subModules[j].backEndFilters.mainModule}/${MODEL[1][MAIN_MODULES[i]].subModules[j].backEndFilters.subModule}?${MODEL[1][MAIN_MODULES[i]].subModules[j].backEndFilters.limit}&fields=`;
    
    // Add fields/columns to be searched on to url
    MODEL[1][MAIN_MODULES[i]].subModules[j].allHeaders.map((header) => {
        if (header.active === true) {
            url += header.value + ',';
        }
    });

    // Remove trailing comma so the sql query doesn't break
    url = url.slice(0, -1);
    
    // Send HTTP GET request
    await axios.get(url, { headers: { Authorization: `Bearer ${localStorage.getItem("access-token")}` } })
        .then(response => {
            success = response.data.success;
            responseData = response;
        })
        .catch(error => console.log('Error:', error));
    
    // Check if HTTP request was successful
    expect(success).toBe(true);

    // Set-up wrapper options
    const wrapperOptions = {
        localVue,
        propsData: {
            searchModule: MODEL[1][MAIN_MODULES[i]].subModules[j],
            query: 'test'
        },
        mocks: {
            $axios: {
                create: () => {
                    return {
                        baseURL: API_ENDPOINT,
                        headers: `Bearer ${localStorage.getItem("access-token")}`,
                        get: jest.fn(() => Promise.resolve(responseData))
                    };
                },
            }
        }
    };
    
    // Prep spies for our component methods we want to validate
    const spyGetNumberOfResults = jest.spyOn(SearchTable.methods, 'getNumberOfResults');
    const spySearch = jest.spyOn(SearchTable.methods, 'search');

    // Mount the component we're testing
    const wrapper = mount(SearchTable, wrapperOptions);

    // Set component data variable
    wrapper.setData({
        count: 0,
        countLoading: false,
        // If true, debug lines log to console, else they don't, set to false prior to release
        debug: false,
        dialog: false,
        intraTableDialog: false,
        expanded: [],
        expandableDataCheck: false,
        frontEndFilters: [],
        itemsOnScreen: null,
        generalSearch: '',
        ignoreCount: false,
        // Set this to true for the test
        regen: true,
        results: [],
        strictSearch: false,
        selectedColumnHeaders: [],
        stagedHeaders: [],
        correctStagedHeaders: [],
        selected: [],
        tableLoading: false,
        intraTableQuery: ''
    })

    // Trigger initial search method to get # of results
    wrapper.vm.getNumberOfResults();

    // Wait for DOM to update
    await wrapper.vm.$nextTick();
    
    // Check if the method was actually called
    expect(spyGetNumberOfResults).toHaveBeenCalled();
    
    // Expect no error from the promise in the function
    expect(spyGetNumberOfResults).not.toThrowError();

    // Expect there the count to be greater than or equal to 0
    expect(parseInt(wrapper.vm.count)).toBeGreaterThanOrEqual(0);

    // Wait for DOM to update
    await wrapper.vm.$nextTick();

    // Check to see if the "search" method was triggered after receiving results
    expect(spySearch).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)

但是,如果我只是注释掉该行:

expect(spyGetNumberOfResults).not.toThrowError();
Run Code Online (Sandbox Code Playgroud)

我没有收到任何错误并且我的测试通过了,所以我使用“not.toThrowError()”的方式显然有问题,但错误消息对我来说信息量不大,有人建议我添加 {"loose": true}到我的 .babelrc 配置文件,但这没有任何作用,我是 Jest 新手,不知道为什么会发生这种情况,感谢任何帮助,提前致谢。

Edu*_*rdo 5

toThrowError或者not.toThrowError不能在间谍功能上调用。文档中有一个很好的例子:

test('throws an error', () => {
  expect(() => {
    SearchTable.getNumberOfResults(); // There must be your call
  }).toThrow();
});
Run Code Online (Sandbox Code Playgroud)