不能开玩笑地通过端点发布

rd9911

我正在做这个小练习并为它编写测试。我所有使用GET端点 ('/api/blogs') 的测试都在工作,但是当涉及到POST数据时,它给出了一个奇怪的对象:

{
      '$__': {
        strictMode: true,
        getters: {},
        _id: '60c5d31b1fd4814db33f879e',
        wasPopulated: false,
        activePaths: { paths: [Object], states: [Object], stateNames: [Array] },
        pathsToScopes: {},
        cachedRequired: {},
        session: null,
        '$setCalled': {},
        emitter: { _events: {}, _eventsCount: 0, _maxListeners: 0 },
        '$options': { defaults: true }
      },
      isNew: true,
      '$locals': {},
      '$op': null,
      _doc: {
        _id: '60c5d31b1fd4814db33f879e',
        title: 'Suomi',
        author: 'Ler',
        url: 'ola.com',
        likes: 9
      }
    }

是github中的整个项目。

这是我想通过的测试: blog.test.js

describe('post', () => {
    test('post a blog', async () => {
        const blogs = await testHelper.blogsInDB();
        const blog = new Blog({
            title: 'Suomi',
            author: 'Ler',
            url: 'ola.com',
            likes: 9
        });
        await api.post('/api/blogs')
            .send(blog)
            .expect(201)
            .expect('Content-Type', /application\/json/);
        expect(await testHelper.blogsInDB()).toHaveLength(blogs.length + 1);
    });

这是接收请求的路由器 blogs.js

blogRouter.post('/', async (req, res) => {
    const body = req.body;
    console.log(body);
    if (body.title === undefined && body.url === undefined) {
        res.status(400).send({error: 'Missing data'});
        return;
    }
    const blog = new Blog({
        title: body.title,
        author: body.author,
        url: body.url,
        likes: body.likes ? body.likes : 0
    });
  
    const result = await blog.save();
    res.status(201).json(result);
});

注意:当我删除if逻辑测试时。此外,Postman 一切正常。在我的测试中,如果我使用obj.save()保存一个新对象但我还需要确保我可以通过端点发布。所以我需要使用req.body.title.

  1. 那么为什么我从 Postman 和我的测试中得到两种不同的回应?
  2. 如何通过端点 ('/api/blogs') 发帖?

任何帮助将不胜感激!

党科亭

我认为您不需要new Blog在测试中使用,它会创建一个 Mongoose 文档的实例(日志中的奇怪对象)。创建 Mongoose 文档是 API 的工作。您只需要发送 Javascript 对象。

describe('post', () => {
    test('post a blog', async () => {
        const blogs = await testHelper.blogsInDB();
        const blog = { // just send the javascript object
            title: 'Suomi',
            author: 'Ler',
            url: 'ola.com',
            likes: 9
        };
        await api.post('/api/blogs')
            .send(blog)
            .expect(201)
            .expect('Content-Type', /application\/json/);
        expect(await testHelper.blogsInDB()).toHaveLength(blogs.length + 1);
    });

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章